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(desktop): stop only the verified desktop Runtime and own installer trees (#2242)

Call White84c55de35c71
diff --git a/core/process_isolation.py b/core/process_isolation.py
index 01fc04e20..89f53a8d8 100644
--- a/core/process_isolation.py
+++ b/core/process_isolation.py
@@ -823,8 +823,12 @@ def reap_orphaned_process_tree(
return "unconfirmed"
-def _processes_carrying_marker(worker_fingerprint: str) -> list[psutil.Process]:
- """This user's live, inspectable processes whose marker hashes to ``worker_fingerprint``.
+def processes_carrying_marker(
+ worker_fingerprint: str,
+ *,
+ marker_env: str = PROCESS_IDENTITY_ENV,
+) -> list[psutil.Process]:
+ """This user's live, inspectable processes whose ``marker_env`` hashes to ``worker_fingerprint``.
Best effort by design. The marked tree is a same-user, non-setuid process
this service spawned, so its ownership and environment are readable; a process
@@ -837,7 +841,11 @@ def _processes_carrying_marker(worker_fingerprint: str) -> list[psutil.Process]:
own_uid = os.getuid() if hasattr(os, "getuid") else None
own_user = None if own_uid is not None else psutil.Process(own_pid).username()
found: list[psutil.Process] = []
- for process in psutil.process_iter(["uids", "username"]):
+ # The cached iteration skips, once, a pid psutil has flagged as reused, so
+ # a rescan could miss that pid's new holder. Each scan starts fresh.
+ psutil.process_iter.cache_clear()
+ # psutil rejects an attribute its platform lacks, and Windows has no uids.
+ for process in psutil.process_iter(["uids"] if own_uid is not None else ["username"]):
if process.pid == own_pid:
continue
if own_uid is not None:
@@ -847,7 +855,7 @@ def _processes_carrying_marker(worker_fingerprint: str) -> list[psutil.Process]:
elif process.info.get("username") != own_user:
continue
try:
- marker = process.environ().get(PROCESS_IDENTITY_ENV)
+ marker = process.environ().get(marker_env)
except (psutil.Error, OSError):
# Exited, or not inspectable and therefore not a tree this service spawned.
continue
@@ -879,7 +887,7 @@ def reap_marked_processes(
if not is_valid_worker_fingerprint(worker_fingerprint):
return "gone"
try:
- victims = _processes_carrying_marker(worker_fingerprint)
+ victims = processes_carrying_marker(worker_fingerprint)
if not victims:
return "gone"
logger.warning("Reaping %d %s process(es) found by their identity marker", len(victims), label)
@@ -895,7 +903,7 @@ def reap_marked_processes(
except psutil.NoSuchProcess:
continue
_gone, alive = psutil.wait_procs(alive, timeout=terminate_timeout)
- if not alive and not _processes_carrying_marker(worker_fingerprint):
+ if not alive and not processes_carrying_marker(worker_fingerprint):
return "reaped"
except Exception as exc:
if on_error is not None:
diff --git a/docs/plans/desktop-runtime-scoped-stop.md b/docs/plans/desktop-runtime-scoped-stop.md
new file mode 100644
index 000000000..8d5cd5160
--- /dev/null
+++ b/docs/plans/desktop-runtime-scoped-stop.md
@@ -0,0 +1,271 @@
+# Desktop Runtime scoped stop and installer ownership
+
+Refs #2135 (Python half), #2131.
+
+## Outcome and boundaries
+
+A desktop app must update smoothly and never stop a Runtime it did not start.
+Authority to stop follows provenance: the desktop host knows which Runtime id its
+bundle started, and asks Python to stop only processes that carry that id. The
+scoped stop reads no file: no pidfile, lock record or installer record decides
+what is signalled. `/ready` and `/internal/health` are unchanged, and so are
+plain `vibe stop` and `vibe stop --receipt`.
+
+## `vibe stop --expect-runtime-id <RUNTIME_ID>`
+
+`RUNTIME_ID` is the 64-character lowercase hex `AVIBE_DESKTOP_RUNTIME_ID` the
+desktop host exports to the Runtime it launches. Every process that Runtime
+starts inherits it. The flag is mutually exclusive with `--receipt`.
+
+### Discovery is one scan
+
+`runtime.stop_desktop_runtime` scans this user's processes once, through
+`core.process_isolation.processes_carrying_marker`, for those whose inherited
+`AVIBE_DESKTOP_RUNTIME_ID` hashes to the expected id. Each one is classified by
+its environment, then by the exact argv shape Avibe launches that role with.
+Only the arguments Avibe writes decide; the program in front of them is whatever
+interpreter, configured executable or shim runs them. An agent's command line is
+arbitrary text, so words it merely contains, such as
+`rg vibe.ui_server run_ui_server` or `rg opencode serve`, name no role:
+
+| Role | Recognized by |
+| --- | --- |
+| `installer` | `AVIBE_DESKTOP_ROLE=installer` in its environment, whatever it runs |
+| `service` | runs `vibe/service_main.py` (argv only, so a bundle an update replaced or moved is still recognized), or the development `main.py` |
+| `ui` | `<interpreter> -c "from vibe.ui_server import run_ui_server; …"`, the launch `start_ui` and the UI restart have always used |
+| `opencode` | `AVIBE_DESKTOP_ROLE=opencode`, which the server manager stamps on the server, and argv ending with `serve --hostname=… --port=…`, the arguments it appends to `agents.opencode.cli_path`, whether that runs natively, through an npm install's `node` shim or as a wrapper. The agent work the server runs inherits the stamp, and those arguments are common to servers, so neither decides alone |
+| `unknown` | carries the id, but its command line cannot be read |
+| none | any other program: agent CLIs, the tunnel connector |
+
+- The stop process and its ancestors carry the id when the desktop host
+ started the stop, and are never signalled.
+- A signal goes only to a handle the scan returned, and only while
+ `is_running()` holds for it. psutil compares the birth time it read at the
+ scan, and `send_signal`/`terminate`/`kill` refuse a reused pid themselves.
+- Each scan clears psutil's `process_iter` cache: the cached iteration skips,
+ once, a pid it has flagged as reused, which would hide that pid's new holder
+ from the rescan.
+- The scan asks psutil only for what the platform has: uids on POSIX, the
+ username on Windows, where psutil refuses to collect uids at all.
+
+### Order and postcondition
+
+1. Service processes, then UI processes: SIGTERM, then SIGKILL after 5 s.
+2. Backend installer trees of this Runtime whose owning UI has exited, by the
+ owner each tree names (see below). A tree whose owner is still alive stays,
+ and the rescan reports it. Their staging and records stay for the next
+ claim of their backend root.
+3. The OpenCode server.
+4. A rescan decides the outcome. Any role process still carrying the id,
+ including one started after the scan or one in the stop's own lineage,
+ fails the stop.
+
+`unknown` processes and programs without a role are never signalled.
+
+### Presence and outcome
+
+`runtime.DesktopRuntimePresence` is `MATCH` when the scan finds a role process.
+Otherwise the service lock decides without reading its record: free is
+`ABSENT`, held by another handle is `MISMATCH`, and a lock that cannot be
+probed, including a lock call that fails for any other reason, is `UNKNOWN`.
+The desktop host mirrors these as Mine, Absent, Foreign and Unknown.
+`runtime.DesktopRuntimeStopOutcome` is `NOT_OURS` (nothing signalled),
+`STOPPED` or `FAILED`.
+
+| Situation | Exit | stderr | Effects |
+| --- | --- | --- | --- |
+| Invalid id | 3 | `{"reason":"invalid_runtime_id"}` | none |
+| No role process carries the id, and the service lock is held | 3 | `{"reason":"service_runtime_id_mismatch"}` | none |
+| No role process carries the id, and the lock cannot be probed | 3 | `{"reason":"service_identity_unavailable"}` | none |
+| Nothing carries the id, and the lock is free | 0 | none | status `stopped` |
+| Every role process carrying the id stopped | 0 | `{"left_running":[{"pid":…,"name":…}]}` when other programs carry the id | status `stopped` while the lock is free |
+| A role process carrying the id is left | 2 | localized error, then `{"failed":"<part>","remaining":[{"pid":…,"role":…}]}` | status `error` while the lock is free |
+
+The status file belongs to the service holding the service lock. The stop
+writes it only while it holds the free lock itself, so no service can start,
+and publish its own status, before the write lands. When a service holds the
+lock, whether a successor started before an earlier stop of this id finished or
+this Runtime's own service that did not stop, or the lock cannot be probed, the
+stop leaves the status file alone, whether it succeeded or failed.
+
+`<part>` is the first of `service`, `ui`, `installer`, `opencode` and `unknown`
+that did not stop. Refusal happens before anything is signalled; installers
+and the status file are untouched. The JSON lines are the machine contract and
+are never localized; the exit-2 diagnostics go through `vibe/i18n/`
+(`runtime.stop.*`) and are shared with the full stop.
+
+## Handover
+
+When a desktop `vibe start` finds a controller whose health names another
+desktop Runtime id, it calls the same `runtime.stop_desktop_runtime` with that
+observed id and fails the start if the stop is refused or fails. It also fails
+the start if the UI pidfile still names a running UI afterwards: that UI is not
+the superseded Runtime's, and the start would otherwise reuse it or replace it
+with an unscoped stop. The tunnel connector is left for the successor to adopt.
+These errors go through `vibe/i18n/` (`desktopRuntime.handover*`).
+
+## Backend installer ownership (#2131)
+
+- The UI process that starts an installer owns its tree. npm and the installed
+ executable's `--version` probe start at one spawn point,
+ `desktop_backends._spawn_owned_installer`: in their own process group, with a
+ fresh `AVIBE_PROCESS_IDENTITY` marker, `AVIBE_DESKTOP_ROLE=installer`, the
+ UI's `AVIBE_DESKTOP_RUNTIME_ID`, `AVIBE_DESKTOP_INSTALLER_OWNER=<pid>:<create
+ time>` of the UI, and a durable record under
+ `<runtime dir>/desktop-backend-installs/`. Every member inherits the four
+ variables, so a process scan finds the whole tree and its owner.
+- The role variable exists because nothing else says "installer": watch
+ workers, command runners and the Model Hub supervisor carry
+ `AVIBE_PROCESS_IDENTITY` too. The spawn point sets the Runtime id itself
+ because the installer environment is an allowlist without `AVIBE_*`.
+- Ownership travels with the tree. A tree is abandoned when no process has
+ its owner's pid. While that pid keeps its create time
+ (`runtime.process_create_time`, exact equality) the owner is alive. macOS can
+ shift the create time psutil shows for a process that keeps running (#2129),
+ so a different one alone proves nothing: the pid was reused only when the
+ process holding it is readable and is not a UI of the tree's Runtime, known
+ by the launch shape and id the scoped stop's scan uses
+ (`runtime.is_desktop_ui`). A missing or malformed owner value, or a different
+ create time on a process that cannot be read, fails closed: the reap reports
+ failure and stops nothing. One function,
+ `desktop_backends.reap_abandoned_desktop_backend_installs`, applies this for
+ every caller, so no caller's registry, pidfile or knowledge of the UI decides.
+ The owner registry serves only the owner's own drain.
+- Records serve only the claim's cleanup of the staging they name.
+- The record names the install's staging directory and lives exactly as long
+ as the install: the install holds `.install.lock` from before the record is
+ written until after it has removed its staging and then the record.
+- After npm exits, times out, or the owner shuts down, the owner stops the
+ leader, waits for its group, and reaps any member by group and by marker.
+ `.install.lock`, the staging directory and the record are released only after
+ the tree is shown gone. If it cannot be shown gone, the install fails with
+ `install_drain_failed`, and the lock, the staging and the record stay.
+- The owner drains on its stop signal (`handle_exit`) and on lifespan shutdown,
+ then refuses new installs (`install_shutting_down`). The probe is an owned
+ installer, so a drain during it stops it too.
+- Every acquisition of `.install.lock` goes through one function,
+ `desktop_backends._claim_backend_root`. Under the lock the claim first reaps
+ every abandoned installer tree of its Runtime id. Its own trees, and those of
+ another live UI of the same id, have a live owner and stay. Then every record
+ of the root belongs to an install whose owner died holding the lock: the
+ claim reaps its tree by marker, removes its staging, and then the record. So
+ a UI that replaces one killed mid-install reaps first, and never installs
+ over a tree that may still be writing.
+- The claim lists records with `os.scandir`. Any `OSError` on the directory or
+ on a record makes the listing unknown: the claim removes nothing and refuses
+ with `install_locked`. Only a missing directory reads as "no records", and a
+ record gone mid-listing is skipped because its install finished. A tree that
+ cannot be shown gone also refuses the claim.
+- The stops read no record. `vibe stop --expect-runtime-id` for the id it
+ names, and `vibe stop` and the restart supervisor for their own, stop the UI
+ and then reap the abandoned installer trees. `vibe stop` reaps before it
+ reports a service or UI that did not stop. A tree whose owner is alive,
+ such as the install of a UI a missing or corrupt pidfile hid from the full
+ stop, stays. A tree that cannot be shown gone, or whose owner cannot be told,
+ fails the stop (exit 2) or the restart. Staging and records stay for the next
+ claim.
+- Removal is confined by the record's shape: only a normalized absolute path
+ named `.staging-<32 hex>` directly inside a directory named after a backend
+ qualifies. A record naming anything else is discarded as invalid and its
+ path is never removed.
+- A record that cannot be read is unknown, not invalid, and is kept: the claim
+ refuses with `install_locked`.
+- The OpenCode server and UI pidfiles are written atomically, so no reader
+ sees a half-written record.
+
+## Known limits
+
+- Nothing locks the Runtime across processes. A process that starts carrying
+ the id after the scan is never signalled; the rescan reports it and the stop
+ exits 2.
+- A process whose environment cannot be read is not seen by the scan. Processes
+ a desktop Runtime starts are same-user and inspectable.
+- A service started from a development `main.py` is recognized only while its
+ checkout still has that layout on disk. Desktop bundles run
+ `vibe/service_main.py`, which is recognized from argv alone.
+- `write_shutdown_intent` keeps one record, so with several targets the last
+ one written wins.
+- An OpenCode server a successor adopted still carries the old id and is
+ stopped with it, as before.
+- An OpenCode server started by a release before the stamp is listed in
+ `left_running` and not signalled. The handover of those releases never
+ stopped OpenCode either.
+- Agent work an OpenCode server runs inherits the stamp, so one of its
+ programs whose argv ends with `serve --hostname=… --port=…` is taken for an
+ OpenCode server.
+- Role classification guards against accidental collisions, not mimicry. An
+ agent process already runs with the user's full authority and could signal
+ the service itself, so a process deliberately shaped like a role is not a
+ boundary the scan defends. Every descendant of the service inherits every
+ variable it carries, so no inherited marker separates the service from its
+ agent tasks, and the service is known by its launch shape and the id alone:
+ a process carrying the id that runs a file ending in `vibe/service_main.py`
+ is stopped with the Runtime it belongs to.
+- An owner killed between creating its staging directory and writing its record
+ leaves an almost empty staging directory that no record names.
+- `vibe stop` and a claim scan only for installer trees of their own Runtime
+ id; from a terminal that means the ones without an id. A tree another
+ Runtime id left, for example before an update, is stopped by the desktop
+ host's scoped stop of that id, or reaped by the next claim of its backend
+ root through the record it left.
+- Plain `vibe stop` and the restart supervisor still find the UI by its
+ pidfile, as before this change. With that pidfile missing or corrupt the UI
+ keeps running; only its installs are no longer at risk.
+
+## Known-by-design ledger
+
+- Programs without a role that carry the id, such as agent CLIs and the tunnel
+ connector, are listed in `left_running` and never signalled. They are either
+ children of a stopped role process or, like the connector, kept for adoption.
+- The scoped stop does not stop remote access: that path acts on the
+ connector's files. The handover leaves the tunnel for the successor.
+- A role process in the stop's own lineage is never signalled and fails the
+ stop; a program without a role in the lineage is not listed.
+- The scoped stop path reads no file: no pidfile, lock record or installer
+ record. Installer trees are found by the scan like every other role; their
+ staging and records wait for the next claim of their backend root.
+- A claim whose leftover staging cannot be removed still proceeds. The failure
+ is logged with the path, the record stays, and the next claim retries.
+ Refusing with `install_locked` would let one undeletable directory block that
+ backend for good; every install uses a fresh staging directory, so the
+ leftover costs only disk.
+- Full `vibe stop` keeps OpenCode non-fatal. The desktop host consumes the
+ scoped result to replace or remove the bundle OpenCode runs from, so there a
+ surviving OpenCode of this id fails the stop (exit 2). Plain `vibe stop` is
+ also called by people and by the upgrade and restart flows; changing its exit
+ code would widen this change beyond the desktop. A test pins both.
+- A non-desktop `vibe start` still replaces an unhealthy UI through `stop_ui`,
+ unchanged.
+- The start side of the handover claims by pidfile, lock and command line, as
+ on master. A service another desktop Runtime starts after the scan can be
+ reused under the wrong id, and a live foreign UI whose command line cannot be
+ read passes the UI check. A handover check is check-then-act, so the fix
+ belongs at the start claim points (`_resolve_service_pid`, `start_ui` reuse
+ or replace): with an expected id, claim only processes that carry this
+ Runtime id. Tracked in #2135.
+- If this stop's ancestors cannot all be read, its lineage falls back to its
+ pid and parent pid, with a warning; a role process of this Runtime further up
+ the chain could then be signalled.
+- `--expect-runtime-id` help stays English, like every other argparse help
+ string. The diagnostics a stop prints are localized; the JSON lines are not.
+- The expected id comes only from `--expect-runtime-id`, never from the CLI's
+ own environment.
+- An owner's pid taken over by another UI of the same Runtime, after the owner
+ was killed, reads as the owner with a shifted create time, so its tree stays
+ until the next scoped stop, which stops that UI first, or the next claim of
+ its backend root reaps it through its record. That takes a full pid wrap
+ landing on a UI. An owner launched outside the UI's `-c` shape, which Avibe
+ never does, reads as reused on a shifted create time, as before this rule.
+
+## Consumer notes for the desktop host (PR2)
+
+- Pass `--expect-runtime-id` for handover, Quit and uninstall. Exit 3 means
+ nothing was touched; parse the JSON reason. `service_runtime_id_mismatch` is
+ Foreign; `service_identity_unavailable` is Unknown, to be retried and never
+ treated as Absent.
+- Exit 2 means a process or installer tree of this Runtime may still be
+ running: do not replace or remove the bundle. `remaining` names each one.
+- `left_running` lists the other programs carrying the id. For Quit and
+ uninstall the tunnel connector is among them; stop it separately if the
+ tunnel should not outlive the app.
+- Uninstall should take the backend's `.install.lock` before removing its root.
diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.py
index 6424ce09d..d321c335e 100644
--- a/modules/agents/opencode/server.py
+++ b/modules/agents/opencode/server.py
@@ -26,6 +26,7 @@ from typing import Any, Awaitable, Callable, Dict, List, Optional
import aiohttp
from config import paths
+from config.atomic_io import write_atomic
from config.v2_config import V2Config, is_model_hub_enabled
from core.handlers.model_hub.identifiers import OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL
from core.process_isolation import isolated_subprocess_kwargs, terminate_process_tree
@@ -33,6 +34,7 @@ from core.resource_governance import is_controller_resource_governor
from modules.agents.opencode.caller_context import ensure_plugin_installed, server_environment
from modules.agents.opencode.config_reconciler import OpenCodeConfigReconciler
from vibe import runtime
+from vibe.desktop_runtime import DESKTOP_OPENCODE_ROLE, DESKTOP_ROLE_ENV
from vibe.opencode_config import (
OPENCODE_REASONING_VARIANTS,
OpenCodeRuntimeConfigInvalidError,
@@ -750,7 +752,7 @@ class OpenCodeServerManager:
revised["active_run_sessions"] = sorted(retained)
if retained != set(active):
try:
- self._pid_file.write_text(json.dumps(revised))
+ write_atomic(self._pid_file, json.dumps(revised))
except Exception:
logger.warning(
"Could not persist reconciled OpenCode run markers",
@@ -1097,7 +1099,7 @@ class OpenCodeServerManager:
payload["model_hub_overlay_provider_ids"] = list(
self._model_hub_overlay_provider_ids
)
- self._pid_file.write_text(json.dumps(payload))
+ write_atomic(self._pid_file, json.dumps(payload))
except Exception as e:
logger.debug(f"Failed to write OpenCode pid file: {e}")
@@ -1146,7 +1148,7 @@ class OpenCodeServerManager:
if references_current_server:
assert isinstance(info, dict)
info["active_run_sessions"] = sorted(updated)
- self._pid_file.write_text(json.dumps(info))
+ write_atomic(self._pid_file, json.dumps(info))
return updated
def _clear_pid_file(self) -> None:
@@ -1937,6 +1939,7 @@ class OpenCodeServerManager:
logger.info(f"Starting OpenCode server: {' '.join(cmd)}")
env = os.environ.copy()
+ env[DESKTOP_ROLE_ENV] = DESKTOP_OPENCODE_ROLE
env["OPENCODE_ENABLE_EXA"] = "1"
env["OPENCODE_DISABLE_EXTERNAL_SKILLS"] = "1"
env.update(server_environment())
diff --git a/tests/test_desktop_backends.py b/tests/test_desktop_backends.py
index 381b3a502..89390b344 100644
--- a/tests/test_desktop_backends.py
+++ b/tests/test_desktop_backends.py
@@ -2,12 +2,21 @@ from __future__ import annotations
import json
import os
+import secrets
+import signal
import subprocess
+import sys
+import threading
+import time
from pathlib import Path
+import psutil
import pytest
+from config import paths as config_paths
+from storage.lock import MigrationFileLock, MigrationLockTimeout
from vibe import desktop_backends
+from vibe.runtime import pid_alive
def _desktop_env(tmp_path: Path) -> dict[str, str]:
@@ -46,6 +55,9 @@ def _fake_npm_install(
spec = desktop_backends.BACKEND_SPECS[backend]
def fake_run(command, *, cwd, env, timeout_seconds):
+ if "--prefix" not in command:
+ # The installed executable's ``--version`` probe.
+ return subprocess.CompletedProcess(command, 0, f"{backend} 1.2.3", "")
staging = Path(command[command.index("--prefix") + 1])
package_dir = staging / "node_modules" / Path(*spec.package_path)
package_dir.mkdir(parents=True)
@@ -109,11 +121,6 @@ def test_install_publishes_verified_native_backend(monkeypatch, tmp_path, backen
env["OPENAI_API_KEY"] = "fixture-key"
calls: list[tuple[list[str], dict[str, str], Path]] = []
monkeypatch.setattr(desktop_backends, "_run_command", _fake_npm_install(backend, calls=calls))
- monkeypatch.setattr(
- desktop_backends.subprocess,
- "run",
- lambda command, **_kwargs: subprocess.CompletedProcess(command, 0, f"{backend} 1.2.3", ""),
- )
activated: list[str] = []
result = desktop_backends.install_desktop_backend(
@@ -163,11 +170,6 @@ def test_codex_accepts_nested_target_package(monkeypatch, tmp_path):
"_run_command",
_fake_npm_install("codex", codex_layout="nested"),
)
- monkeypatch.setattr(
- desktop_backends.subprocess,
- "run",
- lambda command, **_kwargs: subprocess.CompletedProcess(command, 0, "codex-cli 1.2.3", ""),
- )
result = desktop_backends.install_desktop_backend("codex", base_env=env)
@@ -224,11 +226,6 @@ def test_failed_install_keeps_current_descriptor_and_removes_staging(monkeypatch
def test_descriptor_publication_failure_does_not_activate_config(monkeypatch, tmp_path):
env = _desktop_env(tmp_path)
monkeypatch.setattr(desktop_backends, "_run_command", _fake_npm_install("opencode"))
- monkeypatch.setattr(
- desktop_backends.subprocess,
- "run",
- lambda command, **_kwargs: subprocess.CompletedProcess(command, 0, "opencode 1.2.3", ""),
- )
state = {"path": "opencode"}
def activate(path):
@@ -263,11 +260,6 @@ def test_descriptor_is_published_before_activation_and_restored_on_failure(monke
backend_root.mkdir(parents=True, exist_ok=True)
(backend_root / "current.json").write_text(json.dumps(old_descriptor), encoding="utf-8")
monkeypatch.setattr(desktop_backends, "_run_command", _fake_npm_install("claude"))
- monkeypatch.setattr(
- desktop_backends.subprocess,
- "run",
- lambda command, **_kwargs: subprocess.CompletedProcess(command, 0, "claude 1.2.3", ""),
- )
def fail_activation(new_path):
assert desktop_backends.resolve_published_desktop_backend("claude", env) == new_path
@@ -315,3 +307,653 @@ def test_resolver_rejects_descriptor_traversal_and_non_native_file(tmp_path):
encoding="utf-8",
)
assert desktop_backends.resolve_published_desktop_backend("codex", env) is None
+
+
+# --- The installer tree is owned by the process that started it (#2131) ---
+
+_REPO_ROOT = Path(__file__).resolve().parents[1]
+# Random, so no process another test file started is ever in scope.
+_TREE_RUNTIME_ID = secrets.token_hex(32)
+# npm-shaped: the leader starts one child in its group and one that leaves it
+# (and ignores SIGTERM), then works until stopped. Each child names the test's
+# temporary directory, which is how the conftest signal guard knows it as this
+# test's own once its leader no longer parents it.
+_INSTALLER_TREE_SCRIPT = """
+import json, os, subprocess, sys, time
+member = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)", {pids!r}])
+escaped = subprocess.Popen(
+ [sys.executable, "-c", "import signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(120)", {pids!r}],
+ start_new_session=True,
+)
+with open({pids!r} + ".tmp", "w") as handle:
+ json.dump([os.getpid(), member.pid, escaped.pid], handle)
+os.replace({pids!r} + ".tmp", {pids!r})
+time.sleep(120)
+"""
+# `start_ui` launches the UI, the only process that installs, as `<python> -c "<this>..."`.
+_UI_LAUNCH = "from vibe.ui_server import run_ui_server; "
+_INSTALL_OWNER_SCRIPT = (
+ _UI_LAUNCH
+ + """import json, sys
+from vibe import desktop_backends
+desktop_backends.install_desktop_backend("claude", base_env=json.loads(sys.argv[1]))
+"""
+)
+
+
+def _installer_env(tmp_path: Path, npm_script: str) -> dict[str, str]:
+ env = _desktop_env(tmp_path)
+ node = Path(env["VIBE_SHOW_RUNTIME_NODE_BIN"])
+ node.write_text(f'#!/bin/sh\nexec "{sys.executable}" "$@"\n', encoding="utf-8")
+ node.chmod(0o755)
+ Path(env["AVIBE_DESKTOP_NPM_CLI"]).write_text(npm_script, encoding="utf-8")
+ return env
+
+
+def owner_runtime_id(monkeypatch):
+ # The install owner's Runtime id, which every installer it starts inherits.
+ monkeypatch.setenv(desktop_backends.DESKTOP_RUNTIME_ID_ENV, _TREE_RUNTIME_ID)
+ return _TREE_RUNTIME_ID
+
+
+def installer_trees(tmp_path, owner_runtime_id):
+ """Makes install environments, each with its own backend root and npm tree."""
+
+ started: list[int] = []
+
+ def make(name: str):
+ pids_path = tmp_path / name / "installer-pids.json"
+
+ def wait_for_tree() -> list[int]:
+ deadline = time.monotonic() + 15
+ while not pids_path.exists():
+ assert time.monotonic() < deadline, "installer tree did not start"
+ time.sleep(0.05)
+ pids = json.loads(pids_path.read_text(encoding="utf-8"))
+ started.extend(pids)
+ return pids
+
+ return _installer_env(tmp_path / name, _INSTALLER_TREE_SCRIPT.format(pids=str(pids_path))), wait_for_tree
+
+ yield make
+ for pid in started:
+ if pid_alive(pid):
+ os.kill(pid, signal.SIGKILL)
+
+
+def installer_tree(installer_trees):
+ return installer_trees("tree")
+
+
+def children():
+ """Processes a test starts, killed and reaped when it ends."""
+
+ started: list[subprocess.Popen] = []
+ yield started
+ for child in started:
+ if child.poll() is None:
+ child.kill()
+ child.wait(timeout=10)
+
+
+def _running(pids: list[int]) -> list[int]:
+ return [pid for pid in pids if pid_alive(pid)]
+
+
+def _install_records() -> list[Path]:
+ records = config_paths.get_runtime_dir() / "desktop-backend-installs"
+ return sorted(records.glob("*.json")) if records.exists() else []
+
+
+def _install_lock_is_free(env: dict[str, str]) -> bool:
+ lock = MigrationFileLock(
+ Path(env["AVIBE_DESKTOP_BACKENDS_ROOT"]) / "claude" / ".install.lock",
+ timeout_seconds=0,
+ )
+ try:
+ lock.acquire()
+ except MigrationLockTimeout:
+ return False
+ lock.release()
+ return True
+
+
+def _stagings(env: dict[str, str]) -> list[Path]:
+ return sorted((Path(env["AVIBE_DESKTOP_BACKENDS_ROOT"]) / "claude").glob(".staging-*"))
+
+
+def _start_owner(children: list[subprocess.Popen], env: dict[str, str], wait_for_tree) -> list[int]:
+ """A live stand-in for the UI: it installs with ``env`` and owns the tree that starts."""
+
+ children.append(subprocess.Popen([sys.executable, "-c", _INSTALL_OWNER_SCRIPT, json.dumps(env)], cwd=_REPO_ROOT))
+ pids = wait_for_tree()
+ assert _running(pids) == pids
+ return pids
+
+
+def _start_ui_stand_in(children: list[subprocess.Popen], tmp_path: Path, env: dict[str, str]) -> int:
+ """A process launched the way the UI is, running with ``env``."""
+
+ ready = tmp_path / f"ui-{len(children)}.ready"
+ script = _UI_LAUNCH + "import pathlib, sys, time; pathlib.Path(sys.argv[1]).touch(); time.sleep(120)"
+ children.append(subprocess.Popen([sys.executable, "-c", script, str(ready)], cwd=_REPO_ROOT, env=env))
+ deadline = time.monotonic() + 15
+ while not ready.exists():
+ assert time.monotonic() < deadline, "UI stand-in did not start"
+ time.sleep(0.05)
+ return children[-1].pid
+
+
+def _shift_create_time(monkeypatch, pid: int) -> None:
+ """psutil shows ``pid`` started at another time, as macOS can after sleep while it keeps running."""
+
+ from vibe import runtime
+
+ real_create_time = runtime.process_create_time
+ monkeypatch.setattr(
+ runtime, "process_create_time", lambda other: real_create_time(other) + 1.0 if other == pid else real_create_time(other)
+ )
+
+
+def _start_tree_naming(children: list[subprocess.Popen], env: dict[str, str], wait_for_tree, owner: str | None):
+ """An installer tree of this Runtime that names ``owner``, or no owner at all."""
+
+ tree_env = {
+ **os.environ,
+ desktop_backends.DESKTOP_ROLE_ENV: desktop_backends.DESKTOP_INSTALLER_ROLE,
+ desktop_backends.PROCESS_IDENTITY_ENV: desktop_backends.new_process_identity_marker(),
+ }
+ if owner is not None:
+ tree_env[desktop_backends.DESKTOP_INSTALLER_OWNER_ENV] = owner
+ npm = Path(env["AVIBE_DESKTOP_NPM_CLI"]).read_text(encoding="utf-8")
+ children.append(subprocess.Popen([sys.executable, "-c", npm], env=tree_env))
+ return wait_for_tree()
+
+
+def _start_killed_owner(env: dict[str, str], wait_for_tree) -> list[int]:
+ """An owner that dies (SIGKILL) mid-install, before it can drain its tree."""
+
+ owner = subprocess.Popen(
+ [sys.executable, "-c", _INSTALL_OWNER_SCRIPT, json.dumps(env)],
+ cwd=_REPO_ROOT,
+ )
+ try:
+ pids = wait_for_tree()
+ finally:
+ owner.kill()
+ owner.wait(timeout=10)
+ assert _running(pids) == pids
+ assert len(_install_records()) == 1
+ assert len(_stagings(env)) == 1
+ return pids
+
+
+def quiet_stop(monkeypatch):
+ from vibe import cli, remote_access, runtime
+
+ # The full stop's service half scans live processes; nothing of this test
+ # runs there, and the real host must not be touched. The UI half reads
+ # only this test's UI pidfile.
+ monkeypatch.setattr(runtime, "stop_service", lambda: False)
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda include_starting=True: None)
+ monkeypatch.setattr(remote_access, "stop", lambda: {"ok": True})
+ monkeypatch.setattr(cli, "_stop_opencode_server", lambda: False)
+ statuses: list[tuple] = []
+ monkeypatch.setattr(cli, "_write_status", lambda *args, **kwargs: statuses.append(args))
+ return cli, statuses
+
+
[email protected](os.name == "nt", reason="POSIX process groups")
+def test_ui_shutdown_signal_drains_the_installer_tree_before_returning(monkeypatch, installer_tree):
+ import uvicorn
+
+ from vibe import ui_server
+
+ monkeypatch.setattr(desktop_backends, "_INSTALLERS_CLOSED", False)
+ env, wait_for_tree = installer_tree
+ outcome: dict[str, str] = {}
+
+ def install() -> None:
+ try:
+ desktop_backends.install_desktop_backend("claude", base_env=env)
+ except desktop_backends.DesktopBackendError as exc:
+ outcome["code"] = exc.code
+
+ worker = threading.Thread(target=install)
+ worker.start()
+ pids = wait_for_tree()
+
+ ui_server._create_ui_server(uvicorn.Config(ui_server.app)).handle_exit(signal.SIGTERM, None)
+
+ assert _running(pids) == []
+ worker.join(timeout=30)
+ assert outcome == {"code": "npm_install_failed"}
+ # The install's own cleanup removes its staging, then its record.
+ assert _install_records() == []
+ assert _install_lock_is_free(env)
+ # A drained owner starts no installer that could outlive it.
+ with pytest.raises(desktop_backends.DesktopBackendError) as refused:
+ desktop_backends.install_desktop_backend("claude", base_env=env)
+ assert refused.value.code == "install_shutting_down"
+
+
[email protected](os.name == "nt", reason="POSIX process groups")
[email protected]("scoped", [False, True], ids=["full", "scoped"])
+def test_stop_reaps_the_tree_of_an_owner_that_died_before_draining(monkeypatch, installer_tree, quiet_stop, scoped):
+ env, wait_for_tree = installer_tree
+ cli, statuses = quiet_stop
+ pids = _start_killed_owner(env, wait_for_tree)
+
+ exit_code = cli.cmd_stop(expect_runtime_id=_TREE_RUNTIME_ID) if scoped else cli.cmd_stop()
+
+ assert exit_code == 0
+ assert _running(pids) == []
+ assert _install_lock_is_free(env)
+ assert statuses == [("stopped",)]
+ # The stop reads no record; its staging and record wait for the next claim.
+ assert len(_stagings(env)) == 1
+ assert len(_install_records()) == 1
+ _patch_fake_install(monkeypatch)
+ desktop_backends.install_desktop_backend("claude", base_env=env)
+ assert _stagings(env) == []
+ assert _install_records() == []
+
+
[email protected](os.name == "nt", reason="POSIX process groups")
[email protected]("failing", ["service", "ui"])
+def test_a_full_stop_that_fails_still_reaps_the_tree_of_a_dead_owner(
+ monkeypatch, installer_tree, quiet_stop, failing
+):
+ from vibe import runtime
+
+ env, wait_for_tree = installer_tree
+ cli, statuses = quiet_stop
+ pids = _start_killed_owner(env, wait_for_tree)
+ # The stop reports this half as still running.
+ if failing == "service":
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda include_starting=True: os.getpid())
+ else:
+ config_paths.get_runtime_ui_pid_path().write_text(str(os.getpid()), encoding="utf-8")
+ monkeypatch.setattr(runtime, "stop_ui", lambda **kwargs: False)
+
+ assert cli.cmd_stop() == 2
+
+ assert _running(pids) == []
+ assert _install_lock_is_free(env)
+ assert statuses == [("error", f"{failing} stop failed")]
+
+
[email protected](os.name == "nt", reason="POSIX process groups")
[email protected]("ui_pidfile", [None, "not-a-pid"], ids=["missing", "corrupt"])
[email protected]("caller", ["stop", "restart"])
+def test_the_tree_of_a_live_owner_stays_whatever_the_ui_pidfile_says(
+ monkeypatch, installer_tree, quiet_stop, children, ui_pidfile, caller
+):
+ from vibe import restart_supervisor
+
+ env, wait_for_tree = installer_tree
+ cli, statuses = quiet_stop
+ pids = _start_owner(children, env, wait_for_tree)
+ config_paths.ensure_data_dirs()
+ if ui_pidfile is not None:
+ config_paths.get_runtime_ui_pid_path().write_text(ui_pidfile, encoding="utf-8")
+
+ if caller == "stop":
+ assert cli.cmd_stop() == 0
+ assert statuses == [("stopped",)]
+ else:
+ seen_at_start: list[list[int]] = []
+
+ def start(start_ui=True):
+ seen_at_start.append(_running(pids))
+ raise RuntimeError("no Runtime starts in this test")
+
+ monkeypatch.setattr(restart_supervisor, "_stop_service_for_restart", lambda: (True, 0.0))
+ monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)
+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", start)
+
+ restart_supervisor._run_restart_job(job_id="jobliveowner", delay_seconds=0, vibe_path="/bin/vibe", trigger="test")
+
+ # The reap let the restart go on to start the successor.
+ assert seen_at_start == [pids]
+ assert _running(pids) == pids
+
+
[email protected](os.name == "nt", reason="POSIX process groups")
+def test_a_live_owner_whose_create_time_shifted_keeps_its_tree(monkeypatch, installer_trees, children):
+ # A Claude install runs, macOS then shows its UI started at another time,
+ # and a second install's claim scans the Runtime for abandoned trees.
+ pids = _start_owner(children, *installer_trees("first"))
+ _shift_create_time(monkeypatch, children[-1].pid)
+ second_env, _ = installer_trees("second")
+ _patch_fake_install(monkeypatch)
+
+ desktop_backends.install_desktop_backend("claude", base_env=second_env)
+
+ assert _running(pids) == pids
+
+
[email protected](os.name == "nt", reason="POSIX process groups")
[email protected]("holder", ["not-a-ui", "ui-of-another-runtime", "ui-without-a-runtime-id"])
+def test_a_tree_whose_owner_pid_now_names_another_process_is_reaped(
+ tmp_path, installer_tree, quiet_stop, children, holder
+):
+ from vibe import runtime
+
+ env, wait_for_tree = installer_tree
+ cli, statuses = quiet_stop
+ # The owner exited and its pid now belongs to a process started later:
+ # this test, or a UI that is not one of this Runtime.
+ if holder == "not-a-ui":
+ pid = os.getpid()
+ else:
+ ui_env = {key: value for key, value in os.environ.items() if key != desktop_backends.DESKTOP_RUNTIME_ID_ENV}
+ if holder == "ui-of-another-runtime":
+ ui_env[desktop_backends.DESKTOP_RUNTIME_ID_ENV] = secrets.token_hex(32)
+ pid = _start_ui_stand_in(children, tmp_path, ui_env)
+ reused = f"{pid}:{runtime.process_create_time(pid) - 1.0!r}"
+ pids = _start_tree_naming(children, env, wait_for_tree, reused)
+
+ assert cli.cmd_stop() == 0
+
+ assert _running(pids) == []
+ assert statuses == [("stopped",)]
+
+
[email protected](os.name == "nt", reason="POSIX process groups")
[email protected]("owner", ["missing", "malformed", "uninspectable"])
[email protected]("scoped", [False, True], ids=["full", "scoped"])
+def test_a_tree_whose_owner_cannot_be_told_fails_every_caller_closed(
+ monkeypatch, installer_tree, quiet_stop, children, capsys, owner, scoped
+):
+ from vibe import runtime
+
+ env, wait_for_tree = installer_tree
+ cli, statuses = quiet_stop
+ named = {"missing": None, "malformed": "not-an-owner"}.get(owner)
+ if owner == "uninspectable":
+ # Shown started at another time, and nothing else about it can be read.
+ live = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"])
+ children.append(live)
+ named = f"{live.pid}:{runtime.process_create_time(live.pid)!r}"
+ _shift_create_time(monkeypatch, live.pid)
+
+ def unreadable(real):
+ def read(process):
+ if process.pid == live.pid:
+ raise psutil.AccessDenied(process.pid)
+ return real(process)
+
+ return read
+
+ for method in ("environ", "cmdline"):
+ monkeypatch.setattr(psutil.Process, method, unreadable(getattr(psutil.Process, method)))
+ pids = _start_tree_naming(children, env, wait_for_tree, named)
+ npm_runs: list[bool] = []
+ _patch_fake_install(monkeypatch, before=lambda: npm_runs.append(True))
+
+ assert (cli.cmd_stop(expect_runtime_id=_TREE_RUNTIME_ID) if scoped else cli.cmd_stop()) == 2
+
+ assert statuses == [("error", "desktop backend install drain failed")]
+ if scoped:
+ reported = json.loads(capsys.readouterr().err.strip().splitlines()[-1])
+ assert reported["failed"] == "installer"
+ assert sorted(item["pid"] for item in reported["remaining"]) == sorted(pids)
+ assert _running(pids) == pids
+ with pytest.raises(desktop_backends.DesktopBackendError) as refused:
+ desktop_backends.install_desktop_backend("claude", base_env=env)
+ assert refused.value.code == "install_locked"
+ assert npm_runs == []
+ assert _running(pids) == pids
+ assert _install_lock_is_free(env)
+
+
[email protected](os.name == "nt", reason="POSIX process groups")
+def test_two_uis_of_one_runtime_each_keep_their_own_tree(installer_trees, children):
+ # Each installs into its own root, so neither waits on the other's lock,
+ # and the second one's claim sees the first one's tree by the Runtime id.
+ first = _start_owner(children, *installer_trees("first"))
+ second = _start_owner(children, *installer_trees("second"))
+
+ assert _running(first) == first
+ assert _running(second) == second
+
+
[email protected](os.name == "nt" or os.geteuid() == 0, reason="POSIX file permissions")
+def test_an_unreadable_records_directory_hides_no_tree_and_authorises_no_cleanup(
+ monkeypatch, installer_tree, quiet_stop
+):
+ env, wait_for_tree = installer_tree
+ cli, statuses = quiet_stop
+ pids = _start_killed_owner(env, wait_for_tree)
+ records = _install_records()
+ records[0].parent.chmod(0)
+ npm_runs: list[bool] = []
+ _patch_fake_install(monkeypatch, before=lambda: npm_runs.append(True))
+ try:
+ # The scan finds the tree; no listing is asked whether one exists.
+ assert cli.cmd_stop(expect_runtime_id=_TREE_RUNTIME_ID) == 0
+ assert _running(pids) == []
+ # An empty or failed listing never reads as "nothing to clean up".
+ with pytest.raises(desktop_backends.DesktopBackendError) as refused:
+ desktop_backends.install_desktop_backend("claude", base_env=env)
+ finally:
+ records[0].parent.chmod(0o700)
+
+ assert refused.value.code == "install_locked"
+ assert npm_runs == []
+ assert _install_records() == records
+ assert len(_stagings(env)) == 1
+ assert _install_lock_is_free(env)
+
+
[email protected](os.name == "nt", reason="POSIX process groups")
+def test_a_drain_during_the_version_probe_does_not_return_while_the_probe_runs(
+ monkeypatch, tmp_path, owner_runtime_id
+):
+ env = _desktop_env(tmp_path)
+ monkeypatch.setattr(desktop_backends, "_INSTALLERS_CLOSED", False)
+ # The installed executable is a script that answers no probe until stopped.
+ monkeypatch.setattr(desktop_backends, "_has_native_magic", lambda _path: True)
+ probe = tmp_path / "probe"
+ fake_npm = _fake_npm_install("claude")
+ real_run = desktop_backends._run_command
+
+ def run(command, **kwargs):
+ if "--prefix" not in command:
+ return real_run(command, **kwargs)
+ completed = fake_npm(command, **kwargs)
+ staging = Path(command[command.index("--prefix") + 1])
+ next(staging.glob("node_modules/@anthropic-ai/*/claude")).write_text(
+ "#!/bin/sh\n"
+ f'echo "$$ $AVIBE_DESKTOP_ROLE $AVIBE_DESKTOP_RUNTIME_ID" > "{probe}.tmp"\n'
+ f'/bin/mv "{probe}.tmp" "{probe}"\n'
+ "exec /bin/sleep 120\n",
+ encoding="utf-8",
+ )
+ return completed
+
+ monkeypatch.setattr(desktop_backends, "_run_command", run)
+ outcome: dict[str, str] = {}
+
+ def install() -> None:
+ try:
+ desktop_backends.install_desktop_backend("claude", base_env=env)
+ except desktop_backends.DesktopBackendError as exc:
+ outcome["code"] = exc.code
+
+ worker = threading.Thread(target=install)
+ worker.start()
+ deadline = time.monotonic() + 15
+ while not probe.exists():
+ assert time.monotonic() < deadline, "the probe did not start"
+ time.sleep(0.05)
+ pid, *inherited = probe.read_text(encoding="utf-8").split()
+ try:
+ drained = desktop_backends.drain_desktop_backend_installs()
+ assert not pid_alive(int(pid))
+ assert drained
+ finally:
+ if pid_alive(int(pid)):
+ os.kill(int(pid), signal.SIGKILL)
+ worker.join(timeout=30)
+
+ # The probe is an installer of this Runtime, which the scoped stop's scan also finds.
+ assert inherited == [desktop_backends.DESKTOP_INSTALLER_ROLE, owner_runtime_id]
+ assert outcome == {"code": "executable_probe_failed"}
+ assert _install_records() == []
+ assert _install_lock_is_free(env)
+
+
[email protected](os.name == "nt", reason="POSIX process groups")
+def test_stop_fails_and_keeps_the_record_when_the_tree_cannot_be_shown_gone(
+ monkeypatch, installer_tree, quiet_stop
+):
+ env, wait_for_tree = installer_tree
+ cli, statuses = quiet_stop
+ _start_killed_owner(env, wait_for_tree)
+ monkeypatch.setattr(desktop_backends, "reap_marked_processes", lambda *args, **kwargs: "unconfirmed")
+
+ assert cli.cmd_stop() == 2
+
+ assert statuses == [("error", "desktop backend install drain failed")]
+ assert len(_install_records()) == 1
+ assert len(_stagings(env)) == 1
+
+
[email protected](os.name == "nt", reason="POSIX process groups")
+def test_install_keeps_its_lock_and_staging_while_its_tree_is_not_shown_gone(monkeypatch, tmp_path):
+ env = _installer_env(tmp_path, "")
+ backend_root = Path(env["AVIBE_DESKTOP_BACKENDS_ROOT"]) / "claude"
+ monkeypatch.setattr(desktop_backends, "_reap_installer_tree", lambda *args: False)
+ outcome: dict[str, str] = {}
+
+ def install() -> None:
+ try:
+ desktop_backends.install_desktop_backend("claude", base_env=env)
+ except desktop_backends.DesktopBackendError as exc:
+ outcome["code"] = exc.code
+
+ worker = threading.Thread(target=install)
+ worker.start()
+ worker.join(timeout=30)
+
+ assert outcome == {"code": "install_drain_failed"}
+ assert not _install_lock_is_free(env)
+ assert list(backend_root.glob(".staging-*"))
+ assert len(_install_records()) == 1
+
+
+def _patch_fake_install(monkeypatch, *, before=None):
+ fake_npm = _fake_npm_install("claude")
+
+ def run(command, **kwargs):
+ if before is not None and "--prefix" in command:
+ before()
+ return fake_npm(command, **kwargs)
+
+ monkeypatch.setattr(desktop_backends, "_run_command", run)
+
+
[email protected](os.name == "nt", reason="POSIX process groups")
+def test_install_reaps_an_abandoned_installer_and_its_staging_before_it_proceeds(monkeypatch, installer_tree):
+ # A UI killed mid-install leaves its tree writing into its staging; the
+ # UI that replaces it must not install on top of that.
+ env, wait_for_tree = installer_tree
+ pids = _start_killed_owner(env, wait_for_tree)
+ seen_by_npm: list[tuple] = []
+ _patch_fake_install(
+ monkeypatch,
+ before=lambda: seen_by_npm.append((_running(pids), len(_stagings(env)), _install_records())),
+ )
+
+ result = desktop_backends.install_desktop_backend("claude", base_env=env)
+
+ # Only the new install's own staging exists when npm runs.
+ assert seen_by_npm == [([], 1, [])]
+ assert result.version == "1.2.3"
+ assert _stagings(env) == []
+ assert _install_lock_is_free(env)
+
+
[email protected](os.name == "nt", reason="POSIX process groups")
+def test_install_is_refused_while_an_abandoned_installer_cannot_be_shown_gone(monkeypatch, installer_tree):
+ env, wait_for_tree = installer_tree
+ _start_killed_owner(env, wait_for_tree)
+ monkeypatch.setattr(desktop_backends, "reap_marked_processes", lambda *args, **kwargs: "unconfirmed")
+ npm_runs: list[bool] = []
+ _patch_fake_install(monkeypatch, before=lambda: npm_runs.append(True))
+
+ with pytest.raises(desktop_backends.DesktopBackendError) as refused:
+ desktop_backends.install_desktop_backend("claude", base_env=env)
+
+ assert refused.value.code == "install_locked"
+ assert npm_runs == []
+ assert _install_lock_is_free(env)
+ assert len(_install_records()) == 1
+ assert len(_stagings(env)) == 1
+
+
+ "recorded",
+ [
+ lambda root, name: str(root / "releases" / name.removeprefix(".staging-")),
+ lambda root, name: str(root / "releases" / name),
+ lambda root, name: os.path.join(str(root), "..", "..", "outside", "claude", name),
+ lambda root, name: os.path.join("claude", name),
+ ],
+ ids=["release", "not-in-a-backend-root", "traversal", "relative"],
+)
+def test_a_recorded_path_outside_a_staging_directory_is_never_removed(monkeypatch, tmp_path, recorded):
+ env = _desktop_env(tmp_path)
+ backend_root = Path(env["AVIBE_DESKTOP_BACKENDS_ROOT"]) / "claude"
+ monkeypatch.chdir(tmp_path)
+ path = Path(recorded(backend_root, f".staging-{'b' * 32}"))
+ (path / "keep").mkdir(parents=True)
+ records = config_paths.get_runtime_dir() / "desktop-backend-installs"
+ records.mkdir(parents=True, exist_ok=True)
+ record = records / f"{'b' * 32}.json"
+ desktop_backends._write_installer_record(
+ record,
+ worker_fingerprint=desktop_backends.fingerprint_process_marker(desktop_backends.new_process_identity_marker()),
+ identity=None,
+ staging=path,
+ )
+ _patch_fake_install(monkeypatch)
+
+ desktop_backends.install_desktop_backend("claude", base_env=env)
+
+ # The record was read, and rejected: it names nothing an install made.
+ assert not record.exists()
+ assert (path / "keep").is_dir()
+
+
[email protected](os.name == "nt" or os.geteuid() == 0, reason="POSIX file permissions")
+def test_an_installer_record_that_cannot_be_read_is_unknown_and_kept(monkeypatch, tmp_path):
+ # Only a record whose content was read and proven invalid is discarded; one
+ # that cannot be read may still name a running installer tree.
+ env = _desktop_env(tmp_path)
+ backend_root = Path(env["AVIBE_DESKTOP_BACKENDS_ROOT"]) / "claude"
+ backend_root.mkdir(parents=True, exist_ok=True)
+ records = config_paths.get_runtime_dir() / "desktop-backend-installs"
+ records.mkdir(parents=True, exist_ok=True)
+ record = records / f"{'c' * 32}.json"
+ desktop_backends._write_installer_record(
+ record,
+ worker_fingerprint=desktop_backends.fingerprint_process_marker(desktop_backends.new_process_identity_marker()),
+ identity=None,
+ staging=backend_root / f".staging-{'c' * 32}",
+ )
+ record.chmod(0)
+ _patch_fake_install(monkeypatch)
+
+ with pytest.raises(desktop_backends.DesktopBackendError) as refused:
+ desktop_backends.install_desktop_backend("claude", base_env=env)
+
+ assert refused.value.code == "install_locked"
+ assert record.exists()
diff --git a/tests/test_desktop_runtime_stop.py b/tests/test_desktop_runtime_stop.py
new file mode 100644
index 000000000..0bbe5d6b3
--- /dev/null
+++ b/tests/test_desktop_runtime_stop.py
@@ -0,0 +1,459 @@
+"""``vibe stop --expect-runtime-id``: a stop that signals only the Runtime it scanned.
+
+Targets are real child processes whose environment does or does not carry
+``AVIBE_DESKTOP_RUNTIME_ID`` and whose command line, or for a backend
+installer whose environment, names the role they stand for. Discovery is
+never substituted: the stop finds them by scanning.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import errno
+import json
+import os
+import secrets
+import shutil
+import signal
+import subprocess
+import sys
+from pathlib import Path
+
+import psutil
+import pytest
+
+from config import paths
+from vibe import cli, desktop_backends, desktop_runtime, remote_access, runtime
+
+# Random, so no process another test file started with a fixed id is ever in scope.
+RUNTIME_ID = secrets.token_hex(32)
+OTHER_ID = secrets.token_hex(32)
+# Printed once the program is running, so it no longer needs its files.
+SLEEP = "import time; print('ready', flush=True); time.sleep(120)"
+REPO_ROOT = Path(__file__).resolve().parents[1]
+# The arguments the OpenCode server manager appends to the configured executable.
+OPENCODE_SERVE = ["serve", "--hostname=127.0.0.1", "--port=4096"]
+# Programs that carry the manager's stamp: the server, and the agent work it runs.
+OPENCODE_STAMPED = {"opencode", "opencode-native", "opencode-configured", "opencode-agent-work"}
+
+pytestmark = pytest.mark.skipif(os.name == "nt", reason="POSIX signal delivery")
+
+
+def bundle(tmp_path) -> Path:
+ """Files shaped like a desktop bundle, so each role runs with the argv Avibe launches it with."""
+
+ root = tmp_path / "bundle"
+ (root / "vibe").mkdir(parents=True)
+ (root / "vibe" / "__init__.py").write_text("", encoding="utf-8")
+ (root / "vibe" / "service_main.py").write_text(SLEEP + "\n", encoding="utf-8")
+ (root / "vibe" / "ui_server.py").write_text(f"def run_ui_server(host, port):\n {SLEEP}\n", encoding="utf-8")
+ # OpenCode runs natively, through an npm install's `node` shim, or as
+ # whatever executable `agents.opencode.cli_path` names; here each is this
+ # interpreter under that name.
+ (root / "bin").mkdir()
+ (root / "bin" / "opencode").write_text(SLEEP + "\n", encoding="utf-8")
+ (root / "serve").write_text(SLEEP + "\n", encoding="utf-8")
+ for name in ("node", "opencode", "my-opencode"):
+ (root / name).symlink_to(sys.executable)
+ return root
+
+
+def argv_for(bundle):
+ def _argv_for(role: str | None) -> list[str]:
+ return {
+ "service": [sys.executable, str(bundle / "vibe" / "service_main.py")],
+ "ui": [sys.executable, "-c", "from vibe.ui_server import run_ui_server; run_ui_server('127.0.0.1', 0)"],
+ # An installer is known by its environment, whatever it runs.
+ "installer": [sys.executable, "-c", SLEEP, "npm-cli.js", "install"],
+ "opencode": [str(bundle / "node"), str(bundle / "bin" / "opencode"), *OPENCODE_SERVE],
+ "opencode-native": [str(bundle / "opencode"), *OPENCODE_SERVE],
+ "opencode-configured": [str(bundle / "my-opencode"), *OPENCODE_SERVE],
+ # Other programs whose command lines only mention a role.
+ "ui-lookalike": [sys.executable, "-c", SLEEP, "vibe.ui_server", "run_ui_server"],
+ "opencode-lookalike": [sys.executable, "-c", SLEEP, "opencode", "serve"],
+ "server-lookalike": [sys.executable, "-c", SLEEP, "app.py", *OPENCODE_SERVE],
+ "opencode-agent-work": [sys.executable, "-c", SLEEP, "agent-tool"],
+ "opencode-server-helper": [sys.executable, "-c", SLEEP, "opencode-server-helper"],
+ None: [sys.executable, "-c", SLEEP, "agent-cli"],
+ }[role]
+
+ return _argv_for
+
+
+def _child_env(runtime_id: str | None, role: str | None = None, owner_pid: int | None = None) -> dict[str, str]:
+ inherited = (desktop_runtime.DESKTOP_RUNTIME_ID_ENV, desktop_runtime.DESKTOP_ROLE_ENV)
+ env = {key: value for key, value in os.environ.items() if key not in inherited}
+ if runtime_id is not None:
+ env[desktop_runtime.DESKTOP_RUNTIME_ID_ENV] = runtime_id
+ if role in OPENCODE_STAMPED:
+ env[desktop_runtime.DESKTOP_ROLE_ENV] = desktop_runtime.DESKTOP_OPENCODE_ROLE
+ if role == "installer":
+ env[desktop_runtime.DESKTOP_ROLE_ENV] = desktop_runtime.DESKTOP_INSTALLER_ROLE
+ env[desktop_backends.PROCESS_IDENTITY_ENV] = desktop_backends.new_process_identity_marker()
+ # Whoever started the tree owns it: this test, unless another process is named.
+ pid = os.getpid() if owner_pid is None else owner_pid
+ env[desktop_runtime.DESKTOP_INSTALLER_OWNER_ENV] = f"{pid}:{runtime.process_create_time(pid)!r}"
+ return env
+
+
+def spawn(argv_for, bundle):
+ children: list[subprocess.Popen] = []
+
+ def _spawn(
+ runtime_id: str | None, role: str | None = "service", owner: subprocess.Popen | None = None
+ ) -> subprocess.Popen:
+ argv = argv_for(role)
+ child = subprocess.Popen(
+ argv,
+ cwd=bundle,
+ env=_child_env(runtime_id, role, None if owner is None else owner.pid),
+ stdout=subprocess.PIPE,
+ text=True,
+ start_new_session=True,
+ )
+ children.append(child)
+ assert child.stdout.readline() == "ready\n"
+ return child
+
+ yield _spawn
+ for child in children:
+ if child.poll() is None:
+ child.kill()
+ child.wait(timeout=10)
+ child.stdout.close()
+
+
+def _alive(child: subprocess.Popen) -> bool:
+ # A signalled child stays a zombie until this test reaps it.
+ return child.poll() is None
+
+
+def stop_env(monkeypatch):
+ """Record every side effect a stop may have."""
+
+ effects: dict[str, list] = {"signals": [], "stop_pid": [], "remote_access": [], "status": []}
+ real_kill = os.kill
+
+ def recording_kill(pid, sig):
+ if sig != 0:
+ effects["signals"].append((pid, sig))
+ return real_kill(pid, sig)
+
+ monkeypatch.setattr(os, "kill", recording_kill)
+ monkeypatch.setattr(runtime, "stop_pid", lambda pid, timeout=5: effects["stop_pid"].append(pid) or False)
+ monkeypatch.setattr(remote_access, "stop", lambda: effects["remote_access"].append(True) or {"ok": True})
+ # The full stop reaps the installers of this process's own Runtime id,
+ # which here would be the host's; the scoped stop reaps those of its id.
+ reap = desktop_backends.reap_abandoned_desktop_backend_installs
+ monkeypatch.setattr(
+ desktop_backends,
+ "reap_abandoned_desktop_backend_installs",
+ lambda runtime_id=None: True if runtime_id is None else reap(runtime_id),
+ )
+ monkeypatch.setattr(cli, "_write_status", lambda *args, **kwargs: effects["status"].append(args))
+ paths.get_runtime_dir().mkdir(parents=True, exist_ok=True)
+ paths.get_logs_dir().mkdir(parents=True, exist_ok=True)
+ return effects
+
+
+def _after_first_scan(monkeypatch, hook) -> list[int]:
+ """Run ``hook`` on the processes the stop's first scan found; returns each scan's size."""
+
+ real_scan = runtime.processes_carrying_marker
+ scans: list[int] = []
+
+ def scan(fingerprint, **kwargs):
+ found = real_scan(fingerprint, **kwargs)
+ scans.append(len(found))
+ if len(scans) == 1:
+ hook(found)
+ return found
+
+ monkeypatch.setattr(runtime, "processes_carrying_marker", scan)
+ return scans
+
+
+def _signalled(effects, child: subprocess.Popen) -> bool:
+ return any(pid == child.pid for pid, _sig in effects["signals"])
+
+
+def _opencode_pid_path():
+ return paths.get_logs_dir() / "opencode_server.json"
+
+
+def _stderr_lines(capsys) -> list[str]:
+ return capsys.readouterr().err.strip().splitlines()
+
+
+def _assert_refused_untouched(stop_env, capsys, reason, *children):
+ assert json.loads(_stderr_lines(capsys)[-1]) == {"reason": reason}
+ assert stop_env["signals"] == []
+ assert stop_env["stop_pid"] == []
+ assert stop_env["remote_access"] == []
+ assert stop_env["status"] == []
+ assert all(_alive(child) for child in children)
+
+
+def test_the_service_ui_installer_and_opencode_carrying_the_id_are_all_stopped(spawn, stop_env, bundle):
+ ui = spawn(RUNTIME_ID, "ui")
+ # Started by the UI, the installer tree is abandoned once the UI has stopped.
+ children = [ui, spawn(RUNTIME_ID, "installer", owner=ui)]
+ children += [spawn(RUNTIME_ID, role) for role in ("service", "opencode", "opencode-native", "opencode-configured")]
+ # An update may already have replaced or moved the files they started from.
+ shutil.rmtree(bundle)
+
+ assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID) == 0
+
+ for child in children:
+ child.wait(timeout=10)
+ assert (child.pid, signal.SIGTERM) in stop_env["signals"]
+ # The tunnel is not stopped through the connector's files; see the ledger.
+ assert stop_env["remote_access"] == []
+ assert stop_env["status"] == [("stopped",)]
+
+
[email protected]("foreign_id", [OTHER_ID, None])
+def test_processes_without_the_id_are_left_running_whatever_the_pidfiles_say(spawn, stop_env, foreign_id):
+ service = spawn(RUNTIME_ID)
+ foreign = {role: spawn(foreign_id, role) for role in ("service", "ui", "installer", "opencode")}
+ paths.get_runtime_pid_path().write_text(str(foreign["service"].pid), encoding="utf-8")
+ paths.get_runtime_ui_pid_path().write_text(str(foreign["ui"].pid), encoding="utf-8")
+ _opencode_pid_path().write_text(json.dumps({"pid": foreign["opencode"].pid, "port": 4096}), encoding="utf-8")
+
+ assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID) == 0
+
+ service.wait(timeout=10)
+ for child in foreign.values():
+ assert _alive(child) and not _signalled(stop_env, child)
+ assert stop_env["stop_pid"] == []
+
+
+def test_a_garbage_opencode_pidfile_does_not_hide_the_opencode_server_carrying_the_id(spawn, stop_env):
+ opencode = spawn(RUNTIME_ID, "opencode")
+ _opencode_pid_path().write_bytes(b"\x00{not json")
+
+ assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID) == 0
+
+ opencode.wait(timeout=10)
+ assert (opencode.pid, signal.SIGTERM) in stop_env["signals"]
+
+
+def test_the_stop_and_its_ancestors_are_never_signalled(spawn, bundle, tmp_path):
+ # The desktop host starts the stop, so the stop and every process above it
+ # carry the id too. Here the parent even looks like this Runtime's UI.
+ service, installer = spawn(RUNTIME_ID), spawn(RUNTIME_ID, "installer")
+ result_path = tmp_path / "stop-result.json"
+ script = (
+ "import json, subprocess, sys\n"
+ f"stop = subprocess.run([sys.executable, '-m', 'vibe', 'stop', '--expect-runtime-id', {RUNTIME_ID!r}],"
+ f" cwd={str(REPO_ROOT)!r}, capture_output=True, text=True)\n"
+ f"open({str(result_path)!r}, 'w').write(json.dumps({{'code': stop.returncode, 'stderr': stop.stderr}}))\n"
+ )
+ parent = subprocess.Popen(
+ [sys.executable, "-c", "from vibe.ui_server import run_ui_server; " + script],
+ cwd=bundle,
+ env=_child_env(RUNTIME_ID),
+ start_new_session=True,
+ )
+ try:
+ parent.wait(timeout=60)
+ finally:
+ if parent.poll() is None:
+ parent.kill()
+ parent.wait(timeout=10)
+
+ # The parent lived to write this, and returned on its own.
+ assert parent.returncode == 0
+ result = json.loads(result_path.read_text(encoding="utf-8"))
+ assert result["code"] == 2
+ reported = json.loads(result["stderr"].strip().splitlines()[-1])
+ assert reported["failed"] == "ui"
+ assert sorted(reported["remaining"], key=lambda item: item["role"]) == [
+ {"pid": installer.pid, "role": "installer"},
+ {"pid": parent.pid, "role": "ui"},
+ ]
+ service.wait(timeout=10)
+ # Its owner, this test, is still alive.
+ assert _alive(installer)
+
+
+ ("role", "failure", "language", "diagnostic"),
+ [
+ ("service", "service", None, "ERROR: Avibe service did not stop; preserving pidfile and aborting."),
+ ("installer", "installer", None, "ERROR: Desktop backend installer processes did not stop."),
+ ("opencode", "opencode", None, "ERROR: The OpenCode server this Runtime started did not stop."),
+ ("opencode", "opencode", "zh", "错误:此 Runtime 启动的 OpenCode 服务未能停止。"),
+ ],
+)
+def test_a_role_process_carrying_the_id_at_the_rescan_fails_the_stop(
+ spawn, stop_env, capsys, monkeypatch, role, failure, language, diagnostic
+):
+ ui = spawn(RUNTIME_ID, "ui")
+ late: list[subprocess.Popen] = []
+ # Started after the scan, it is never signalled; the rescan still sees it.
+ _after_first_scan(monkeypatch, lambda _found: late.append(spawn(RUNTIME_ID, role)))
+ if language is not None:
+ paths.get_config_path().parent.mkdir(parents=True, exist_ok=True)
+ paths.get_config_path().write_text(json.dumps({"language": language}), encoding="utf-8")
+
+ assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID) == 2
+
+ ui.wait(timeout=10)
+ assert _alive(late[0]) and not _signalled(stop_env, late[0])
+ lines = _stderr_lines(capsys)
+ assert lines[-2] == diagnostic
+ assert json.loads(lines[-1]) == {"failed": failure, "remaining": [{"pid": late[0].pid, "role": role}]}
+ assert stop_env["status"] == [("error", cli._STOP_FAILURES[failure][1])]
+
+
+def test_a_pid_recycled_after_the_scan_is_not_signalled(spawn, stop_env, monkeypatch):
+ service = spawn(RUNTIME_ID)
+
+ def recycle(found):
+ for process in found:
+ if process.pid == service.pid:
+ # The scanned process was an earlier holder of this pid.
+ process._ident = (process.pid, process.create_time() - 60)
+
+ scans = _after_first_scan(monkeypatch, recycle)
+
+ assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID) == 2
+
+ assert len(scans) == 2
+ assert _alive(service) and not _signalled(stop_env, service)
+
+
+# A role is the argv shape Avibe launches it with, not words its command line contains.
+# An OpenCode server's arguments decide only with the manager's stamp, which
+# alone decides nothing.
+ "program",
+ [None, "ui-lookalike", "opencode-lookalike", "opencode-server-helper", "server-lookalike", "opencode-agent-work"],
+)
+def test_other_programs_carrying_the_id_are_reported_and_left_running(spawn, stop_env, capsys, program):
+ service, agent = spawn(RUNTIME_ID), spawn(RUNTIME_ID, program)
+
+ assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID) == 0
+
+ service.wait(timeout=10)
+ assert _alive(agent) and not _signalled(stop_env, agent)
+ reported = json.loads(_stderr_lines(capsys)[-1])
+ assert reported == {"left_running": [{"pid": agent.pid, "name": psutil.Process(agent.pid).name()}]}
+ assert stop_env["status"] == [("stopped",)]
+
+
+def test_a_foreign_service_lock_holder_refuses_the_stop(spawn, stop_env, capsys):
+ foreign = spawn(OTHER_ID)
+ lock_path = runtime.get_service_lock_path()
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
+
+ with lock_path.open("w", encoding="utf-8") as held:
+ assert runtime._try_lock_file(held)
+ assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID) == 3
+
+ _assert_refused_untouched(stop_env, capsys, "service_runtime_id_mismatch", foreign)
+
+
[email protected]("late_role", [None, "installer"])
[email protected]("lock", ["held", "unprobeable"])
+def test_a_service_lock_this_runtime_is_not_shown_to_own_keeps_the_shared_status(
+ spawn, stop_env, monkeypatch, lock, late_role
+):
+ # While this Runtime's UI is stopped, a successor's service already holds
+ # the lock, or the lock cannot be probed to show that none does.
+ ui = spawn(RUNTIME_ID, "ui")
+ late: list[subprocess.Popen] = []
+ if late_role is not None:
+ _after_first_scan(monkeypatch, lambda _found: late.append(spawn(RUNTIME_ID, late_role)))
+ lock_path = runtime.get_service_lock_path()
+
+ with contextlib.ExitStack() as stack:
+ if lock == "held":
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
+ assert runtime._try_lock_file(stack.enter_context(lock_path.open("w", encoding="utf-8")))
+ else:
+ lock_path.mkdir(parents=True)
+ assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID) == (0 if late_role is None else 2)
+
+ ui.wait(timeout=10)
+ assert stop_env["status"] == []
+
+
[email protected]("late_role", [None, "installer"])
+def test_no_service_can_take_the_lock_before_the_stop_s_status_lands(spawn, stop_env, monkeypatch, late_role):
+ # A successor's service that takes the lock right after the stop decides
+ # the status is its own would publish a status the stop then overwrites.
+ record = cli._write_status
+ lock_free_at_write: list[bool] = []
+
+ def write(*args, **kwargs):
+ lock_free_at_write.append(runtime.service_instance_lock_available()[0])
+ record(*args, **kwargs)
+
+ monkeypatch.setattr(cli, "_write_status", write)
+ ui = spawn(RUNTIME_ID, "ui")
+ if late_role is not None:
+ _after_first_scan(monkeypatch, lambda _found: spawn(RUNTIME_ID, late_role))
+
+ assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID) == (0 if late_role is None else 2)
+
+ ui.wait(timeout=10)
+ assert len(stop_env["status"]) == 1
+ assert lock_free_at_write == [False]
+
+
+def _lock_path_is_a_directory(monkeypatch):
+ runtime.get_service_lock_path().mkdir(parents=True)
+
+
+def _lock_call_fails(monkeypatch):
+ # Not contention: the lock operation itself failed, so no holder is known.
+ import fcntl
+
+ def _flock(fd, operation):
+ raise OSError(errno.ENOLCK, os.strerror(errno.ENOLCK))
+
+ monkeypatch.setattr(fcntl, "flock", _flock)
+
+
[email protected]("unprobeable", [_lock_path_is_a_directory, _lock_call_fails])
+def test_a_service_lock_that_cannot_be_probed_refuses_the_stop(stop_env, capsys, monkeypatch, unprobeable):
+ unprobeable(monkeypatch)
+
+ assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID) == 3
+
+ _assert_refused_untouched(stop_env, capsys, "service_identity_unavailable")
+
+
+def test_invalid_expected_id_is_refused(stop_env, capsys):
+ assert cli.cmd_stop(expect_runtime_id="A" * 64) == 3
+
+ _assert_refused_untouched(stop_env, capsys, "invalid_runtime_id")
+
+
+def test_with_nothing_running_and_a_free_lock_the_stop_succeeds(stop_env):
+ assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID) == 0
+
+ assert stop_env["signals"] == []
+ assert stop_env["status"] == [("stopped",)]
+
+
+def test_a_full_stop_keeps_a_surviving_opencode_server_non_fatal(spawn, stop_env, monkeypatch):
+ # Only the desktop host replaces the bundle OpenCode runs from; a full stop
+ # also serves people and the upgrade and restart flows, and keeps its exit.
+ opencode = spawn(RUNTIME_ID, "opencode")
+ _opencode_pid_path().write_text(json.dumps({"pid": opencode.pid, "port": 4096}), encoding="utf-8")
+ monkeypatch.setattr(runtime, "stop_service", lambda: False)
+ monkeypatch.setattr(runtime, "stop_ui", lambda: False)
+ monkeypatch.setattr(runtime, "extra_service_process_pids", lambda owner_pid=None: [])
+
+ assert cli.cmd_stop() == 0
+
+ assert stop_env["stop_pid"] == [opencode.pid]
+ assert _alive(opencode)
+ assert stop_env["status"] == [("stopped",)]
diff --git a/tests/test_model_hub_local_error_details.py b/tests/test_model_hub_local_error_details.py
index 3963bf569..dc3776605 100644
--- a/tests/test_model_hub_local_error_details.py
+++ b/tests/test_model_hub_local_error_details.py
@@ -613,6 +613,7 @@ def test_recorded_engine_recovery_preserves_errno_after_record_write(tmp_path, m
def fail(*_args, **_kwargs):
raise OSError(code, "private reason", "/private/凭证")
+ fail.cache_clear = lambda: None
with monkeypatch.context() as patch:
patch.setattr(psutil, "process_iter", fail)
with pytest.raises(EngineUnavailableError) as raised:
@@ -621,7 +622,11 @@ def test_recorded_engine_recovery_preserves_errno_after_record_write(tmp_path, m
assert local_error_detail(raised.value) == f"[Errno {code}] {os.strerror(code)}"
assert json.loads(record.read_text())["engines"]
# A later conclusive pass retires the record and its previous diagnostic.
- monkeypatch.setattr(psutil, "process_iter", lambda *_args: iter(()))
+ def nothing_running(*_args):
+ return iter(())
+
+ nothing_running.cache_clear = lambda: None
+ monkeypatch.setattr(psutil, "process_iter", nothing_running)
assert supervisor._reap_recorded_engines_locked()
assert supervisor._record_os_errno is None
diff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.py
index 0ac310906..a4f626a28 100644
--- a/tests/test_opencode_server.py
+++ b/tests/test_opencode_server.py
@@ -234,6 +234,8 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
create_process.await_args.kwargs["env"]["OPENCODE_DISABLE_EXTERNAL_SKILLS"],
"1",
)
+ # A desktop Runtime's scoped stop knows the server by this stamp.
+ self.assertEqual(create_process.await_args.kwargs["env"]["AVIBE_DESKTOP_ROLE"], "opencode")
def test_terminate_instance_sync_stops_unadopted_managed_server(self):
with tempfile.TemporaryDirectory() as tmp_dir:
@@ -967,8 +969,8 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
await manager.mark_run_active("ses-active")
with patch.object(
- Path,
- "write_text",
+ SERVER_MODULE,
+ "write_atomic",
side_effect=OSError("read-only pid file"),
):
with self.assertRaisesRegex(OSError, "read-only pid file"):
diff --git a/tests/test_process_isolation.py b/tests/test_process_isolation.py
index 3be098085..0fcdf82db 100644
--- a/tests/test_process_isolation.py
+++ b/tests/test_process_isolation.py
@@ -31,7 +31,7 @@ from core.process_isolation import (
process_identity_recycled,
process_identity_subprocess_env,
probe_process_liveness,
- _processes_carrying_marker,
+ processes_carrying_marker,
reap_marked_processes,
reap_orphaned_process_tree,
signal_process_tree,
@@ -561,9 +561,13 @@ def test_marker_scan_skips_processes_it_cannot_inspect(monkeypatch: pytest.Monke
info={"uids": SimpleNamespace(real=own_uid, effective=0, saved=0), "username": "me"},
environ=lambda: pytest.fail("a setuid process cannot carry our marker"),
)
- monkeypatch.setattr(psutil, "process_iter", lambda _attrs: iter([setuid, unreadable, ours]))
+ def process_iter(_attrs):
+ return iter([setuid, unreadable, ours])
- assert _processes_carrying_marker(fingerprint_process_marker(marker)) == [ours]
+ process_iter.cache_clear = lambda: None
+ monkeypatch.setattr(psutil, "process_iter", process_iter)
+
+ assert processes_carrying_marker(fingerprint_process_marker(marker)) == [ours]
assert (
reap_marked_processes(
logging.getLogger(__name__),
diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.py
index 1233e8d50..459399731 100644
--- a/tests/test_restart_supervisor.py
+++ b/tests/test_restart_supervisor.py
@@ -537,6 +537,27 @@ def test_restart_job_continues_when_old_pid_already_exited(monkeypatch, tmp_path
assert runtime.read_json(runtime.get_restart_status_path())["state"] == "succeeded"
+def test_restart_job_does_not_start_while_an_abandoned_installer_tree_survives(monkeypatch, tmp_path):
+ from vibe import desktop_backends
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ calls = []
+
+ monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda stop_ui=True: _fake_stop_runtime(calls))
+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda start_ui=True: _fake_start_runtime(calls))
+ monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)
+ monkeypatch.setattr(desktop_backends, "reap_abandoned_desktop_backend_installs", lambda: False)
+
+ rc = restart_supervisor._run_restart_job(job_id="jobinstall", delay_seconds=0, vibe_path="/bin/vibe", trigger="test")
+
+ assert rc == 2
+ assert calls == ["stop_runtime"]
+ status = runtime.read_json(runtime.get_restart_status_path())
+ assert status["state"] == "failed"
+ assert "desktop backend installer processes did not stop" in status["error"]
+
+
def test_restart_job_aborts_when_extra_service_survives_stop(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
diff --git a/tests/test_runtime_process_scan.py b/tests/test_runtime_process_scan.py
index 92a33bcf3..1cbf44e30 100644
--- a/tests/test_runtime_process_scan.py
+++ b/tests/test_runtime_process_scan.py
@@ -13,6 +13,8 @@ invisible. On Windows it was a ``powershell`` launch, and that is why
"""
import os
+import secrets
+import subprocess
import sys
import threading
import time
@@ -24,6 +26,7 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from vibe import runtime
+from vibe.desktop_runtime import DESKTOP_RUNTIME_ID_ENV
# Generous by design. A scan that only reads what psutil already collected
# finishes in about a second on a CI runner, and the packaging probe allows the
@@ -141,3 +144,31 @@ def test_the_service_scan_finishes_promptly_on_a_real_windows_process_table():
f"service_processes() did not finish within {budget:.1f}s over {visible} processes, "
f"while the raw psutil walk of the same table took {walk_seconds:.2f}s"
)
+
+
[email protected](os.name != "nt", reason="POSIX runs this scan against real processes in test_desktop_runtime_stop")
+def test_the_marker_scan_finds_a_marked_child_on_a_real_windows_process_table():
+ """A scoped ``vibe stop`` finds its targets by this scan.
+
+ psutil refuses to collect an attribute its platform lacks, and a Windows
+ process has no uids, so only a Windows process table shows a scan that
+ raises before it looks at a single process.
+ """
+
+ runtime_id = secrets.token_hex(32)
+ child = subprocess.Popen(
+ [sys.executable, "-c", "import time; print('ready', flush=True); time.sleep(60)"],
+ env={**os.environ, DESKTOP_RUNTIME_ID_ENV: runtime_id},
+ stdout=subprocess.PIPE,
+ text=True,
+ )
+ try:
+ assert child.stdout.readline() == "ready\n"
+ found = runtime.processes_carrying_marker(
+ runtime.fingerprint_process_marker(runtime_id), marker_env=DESKTOP_RUNTIME_ID_ENV
+ )
+ assert child.pid in [process.pid for process in found]
+ finally:
+ child.kill()
+ child.wait(timeout=10)
+ child.stdout.close()
diff --git a/tests/test_runtime_spawn_ownership.py b/tests/test_runtime_spawn_ownership.py
index 005e7b2c9..f529acaae 100644
--- a/tests/test_runtime_spawn_ownership.py
+++ b/tests/test_runtime_spawn_ownership.py
@@ -78,10 +78,11 @@ def _assert_log_sinks_released(spawned: _Spawned) -> None:
def test_a_child_whose_pid_record_cannot_be_written_does_not_survive(spawned, tmp_path: Path) -> None:
- # A real write failure: the record's directory does not exist.
- pid_path = tmp_path / "missing" / "vibe-ui.pid"
+ # A real write failure: where the record's directory should be is a file.
+ (tmp_path / "not-a-directory").write_text("", encoding="utf-8")
+ pid_path = tmp_path / "not-a-directory" / "vibe-ui.pid"
- with pytest.raises(FileNotFoundError):
+ with pytest.raises(OSError):
runtime.spawn_background(_sleeper(), pid_path, "ui_stdout.log", "ui_stderr.log")
_assert_killed_and_reaped(spawned)
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index 0cd36fb64..182aa4009 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -1622,7 +1622,7 @@ def test_cmd_start_ensures_services_without_stopping(monkeypatch):
assert not any(call == "stop" for call in calls)
-def test_desktop_start_hands_over_a_superseded_controller(monkeypatch):
+def _superseded_controller(monkeypatch, result, *, ui_running=False):
calls = []
monkeypatch.setenv("AVIBE_DESKTOP_RUNTIME_ID", "b" * 64)
monkeypatch.setattr(
@@ -1632,27 +1632,43 @@ def test_desktop_start_hands_over_a_superseded_controller(monkeypatch):
)
monkeypatch.setattr(
cli.runtime,
- "resolve_service_owner_pid",
- lambda include_starting: 1234,
- )
- monkeypatch.setattr(cli.runtime, "ui_pid_file_points_to_running_ui", lambda: True)
- monkeypatch.setattr(
- cli.runtime,
- "stop_service",
- lambda: calls.append(("service",)) or True,
- )
- monkeypatch.setattr(
- cli.runtime,
- "stop_ui",
- lambda **kwargs: calls.append(("ui", kwargs)) or True,
+ "stop_desktop_runtime",
+ lambda runtime_id, **kwargs: calls.append((runtime_id, kwargs)) or result,
)
+ monkeypatch.setattr(cli.runtime, "ui_pid_file_points_to_running_ui", lambda: ui_running)
+ return calls
+
+
+def test_desktop_start_hands_over_a_superseded_controller(monkeypatch):
+ calls = _superseded_controller(monkeypatch, cli.runtime.DesktopRuntimeStopResult())
cli._handover_superseded_desktop_runtime()
- assert calls == [
- ("service",),
- ("ui", {"stop_remote_access": False}),
- ]
+ # The Runtime health named is the one stopped, through the scoped stop.
+ assert calls == [("a" * 64, {})]
+
+
+def _left(role):
+ return (cli.runtime.DesktopRuntimeProcess(pid=4242, role=role, name="python"),)
+
+
+ ("result", "ui_running"),
+ [
+ (cli.runtime.DesktopRuntimeStopResult(refusal="service_runtime_id_mismatch"), False),
+ (cli.runtime.DesktopRuntimeStopResult(remaining=_left("service")), False),
+ (cli.runtime.DesktopRuntimeStopResult(remaining=_left("installer")), False),
+ (cli.runtime.DesktopRuntimeStopResult(remaining=_left("opencode")), False),
+ (cli.runtime.DesktopRuntimeStopResult(remaining=_left("unknown")), False),
+ # Stopped, but a UI of some other Runtime still holds the pidfile.
+ (cli.runtime.DesktopRuntimeStopResult(), True),
+ ],
+)
+def test_desktop_start_fails_when_the_superseded_controller_is_not_stopped(monkeypatch, result, ui_running):
+ _superseded_controller(monkeypatch, result, ui_running=ui_running)
+
+ with pytest.raises(RuntimeError):
+ cli._handover_superseded_desktop_runtime()
@pytest.mark.parametrize("controller_runtime_id", [None, "b" * 64])
@@ -1670,13 +1686,8 @@ def test_desktop_start_preserves_external_or_matching_controllers(
)
monkeypatch.setattr(
cli.runtime,
- "stop_service",
- lambda: pytest.fail("controller must be preserved"),
- )
- monkeypatch.setattr(
- cli.runtime,
- "stop_ui",
- lambda **_kwargs: pytest.fail("UI must be preserved"),
+ "stop_desktop_runtime",
+ lambda *_args, **_kwargs: pytest.fail("controller must be preserved"),
)
cli._handover_superseded_desktop_runtime()
@@ -2203,14 +2214,16 @@ def test_cmd_start_leaves_no_ui_running_when_the_ui_pid_record_cannot_be_written
`start_ui` never captured it and the rollback -- which only undoes what it
was told it created -- had nothing to undo. The orphan kept the listener.
Here the real `start_ui` and the real spawn run against a stand-in
- interpreter that just sleeps, and the pid record's directory is missing.
+ interpreter that just sleeps, and a file stands where the pid record's
+ directory would be.
"""
started = _ui_refuses_to_start(monkeypatch, reused=False)
- children = _real_ui_children(monkeypatch, tmp_path, tmp_path / "missing" / "vibe-ui.pid")
+ (tmp_path / "not-a-directory").write_text("", encoding="utf-8")
+ children = _real_ui_children(monkeypatch, tmp_path, tmp_path / "not-a-directory" / "vibe-ui.pid")
try:
- with pytest.raises(FileNotFoundError):
+ with pytest.raises(OSError):
cli.cmd_start()
assert len(children) == 1, children
@@ -4316,12 +4329,15 @@ def test_start_parser_accepts_no_open_browser():
assert args.open_browser is False
[email protected]("receipt", [None, json.dumps(_startup_receipt_payload())])
-def test_stop_parser_and_main_preserve_optional_receipt(monkeypatch, receipt):
- arguments = ["stop"] if receipt is None else ["stop", "--receipt", receipt]
- parsed = cli.build_parser().parse_args(arguments)
- assert parsed.command == "stop"
- assert parsed.receipt == receipt
+ ("arguments", "expected"),
+ [
+ (["stop"], {}),
+ (["stop", "--receipt", json.dumps(_startup_receipt_payload())], {"receipt": json.dumps(_startup_receipt_payload())}),
+ (["stop", "--expect-runtime-id", "a" * 64], {"expect_runtime_id": "a" * 64}),
+ ],
+)
+def test_stop_parser_and_main_route_each_stop_mode(monkeypatch, arguments, expected):
calls = []
monkeypatch.setattr(cli.sys, "argv", ["vibe", *arguments])
monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: None)
@@ -4331,7 +4347,14 @@ def test_stop_parser_and_main_preserve_optional_receipt(monkeypatch, receipt):
cli.main()
assert exited.value.code == 3
- assert calls == ([{}] if receipt is None else [{"receipt": receipt}])
+ assert calls == [expected]
+
+
+def test_stop_parser_rejects_a_receipt_with_an_expected_runtime_id():
+ with pytest.raises(SystemExit):
+ cli.build_parser().parse_args(
+ ["stop", "--receipt", json.dumps(_startup_receipt_payload()), "--expect-runtime-id", "a" * 64]
+ )
def test_remote_parser_accepts_pairing_command():
diff --git a/vibe/cli.py b/vibe/cli.py
index 42538381a..30be6ee4c 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -13651,12 +13651,18 @@ def _handover_superseded_desktop_runtime() -> None:
if actual_runtime_id is None or actual_runtime_id == expected_runtime_id:
return
- service_was_running = runtime.resolve_service_owner_pid(include_starting=True) is not None
- ui_was_running = runtime.ui_pid_file_points_to_running_ui()
- if service_was_running and runtime.stop_service() is not True:
- raise RuntimeError("Failed to stop the superseded desktop-managed Avibe service")
- if ui_was_running and runtime.stop_ui(stop_remote_access=False) is not True:
- raise RuntimeError("Failed to stop the superseded desktop-managed Avibe UI")
+ # Health names the Runtime that answered; the stop signals only processes
+ # that carry its id.
+ result = runtime.stop_desktop_runtime(actual_runtime_id)
+ language = _configured_cli_language()
+ if result.refusal is not None:
+ raise RuntimeError(i18n_t("desktopRuntime.handoverRefused", language, reason=result.refusal))
+ if result.failure is not None:
+ raise RuntimeError(i18n_t("desktopRuntime.handoverFailed", language, part=result.failure))
+ # A UI still running is not the superseded Runtime's. Starting would reuse
+ # it, or replace it with an unscoped stop.
+ if runtime.ui_pid_file_points_to_running_ui():
+ raise RuntimeError(i18n_t("desktopRuntime.handoverForeignUi", language))
def cmd_start(*, open_browser: bool | None = None):
@@ -13923,7 +13929,63 @@ def _stop_receipt_refusal(receipt_json: str) -> str | None:
return None
-def cmd_stop(*, receipt: str | None = None):
+# The part of a stop that did not stop: its localized diagnostic and the
+# status detail, which stays English for machine readers.
+_STOP_FAILURES = {
+ "service": ("runtime.stop.serviceFailed", "service stop failed"),
+ "ui": ("runtime.stop.uiFailed", "ui stop failed"),
+ "installer": ("runtime.stop.installerFailed", "desktop backend install drain failed"),
+ "opencode": ("runtime.stop.opencodeFailed", "opencode stop failed"),
+ "unknown": ("runtime.stop.unknownFailed", "unidentified runtime process left running"),
+}
+
+
+def _stop_failed(part: str, write_status: Callable[..., None] | None = None) -> int:
+ key, detail = _STOP_FAILURES[part]
+ print(i18n_t(key, _configured_cli_language()), file=sys.stderr)
+ (write_status or _write_status)("error", detail)
+ return 2
+
+
+def _write_status_unless_a_service_holds_the_lock(*status: str) -> None:
+ # The service holding the lock owns the shared status, even another
+ # Runtime's. The write holds the free lock, so no service can start, and
+ # publish its own status, before it lands.
+ runtime.desktop_service_lock_presence(while_absent=lambda: _write_status(*status))
+
+
+def _report_opencode_stopped() -> None:
+ print(i18n_t("runtime.stop.opencodeStopped", _configured_cli_language()))
+
+
+def _print_stop_json(payload: dict) -> None:
+ print(json.dumps(payload, separators=(",", ":")), file=sys.stderr)
+
+
+def _stop_expected_desktop_runtime(runtime_id: str) -> int:
+ result = runtime.stop_desktop_runtime(runtime_id)
+ if result.outcome is runtime.DesktopRuntimeStopOutcome.NOT_OURS:
+ _print_stop_json({"reason": result.refusal})
+ return 3
+ if result.left_running:
+ _print_stop_json({"left_running": [{"pid": item.pid, "name": item.name} for item in result.left_running]})
+ if result.opencode_stopped:
+ _report_opencode_stopped()
+ # Unlike a full stop, an OpenCode server of this Runtime that survives
+ # fails this stop: the desktop host replaces or removes the bundle it runs from.
+ if result.outcome is runtime.DesktopRuntimeStopOutcome.FAILED:
+ status = _stop_failed(result.failure, _write_status_unless_a_service_holds_the_lock)
+ remaining = [{"pid": item.pid, "role": item.role} for item in result.remaining]
+ _print_stop_json({"failed": result.failure, "remaining": remaining})
+ return status
+
+ _write_status_unless_a_service_holds_the_lock("stopped")
+ return 0
+
+
+def cmd_stop(*, receipt: str | None = None, expect_runtime_id: str | None = None):
+ if expect_runtime_id is not None:
+ return _stop_expected_desktop_runtime(expect_runtime_id)
if receipt is not None:
reason = _stop_receipt_refusal(receipt)
if reason is not None:
@@ -13934,19 +13996,22 @@ def cmd_stop(*, receipt: str | None = None):
service_stopped = runtime.stop_service()
ui_stopped = runtime.stop_ui()
+ from vibe.desktop_backends import reap_abandoned_desktop_backend_installs
+
+ # Each tree's owner decides whether it is abandoned, so the reap runs
+ # whichever stop above failed.
+ installers_reaped = reap_abandoned_desktop_backend_installs()
# Also terminate OpenCode server on full stop
if _stop_opencode_server():
- print("OpenCode server stopped")
+ _report_opencode_stopped()
if service_was_running and service_stopped is False:
- print("ERROR: Avibe service did not stop; preserving pidfile and aborting.", file=sys.stderr)
- _write_status("error", "service stop failed")
- return 2
+ return _stop_failed("service")
if ui_was_running and ui_stopped is False:
- print("ERROR: Avibe UI did not stop; preserving pidfile and aborting.", file=sys.stderr)
- _write_status("error", "ui stop failed")
- return 2
+ return _stop_failed("ui")
+ if not installers_reaped:
+ return _stop_failed("installer")
_write_status("stopped")
return 0
@@ -16520,10 +16585,16 @@ def build_parser():
subparsers = parser.add_subparsers(dest="command")
stop_parser = subparsers.add_parser("stop", help="Stop all services")
- stop_parser.add_argument(
+ stop_scope = stop_parser.add_mutually_exclusive_group()
+ stop_scope.add_argument(
"--receipt",
help="Stop only if the service identity matches this startup receipt JSON.",
)
+ stop_scope.add_argument(
+ "--expect-runtime-id",
+ metavar="RUNTIME_ID",
+ help="Stop only the processes the desktop Runtime with this id started.",
+ )
start_parser = subparsers.add_parser("start", help="Start services if needed without stopping running processes")
start_parser.add_argument(
"--no-open-browser",
@@ -18667,7 +18738,11 @@ def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:
"""Run the admitted command. Every branch exits; nothing returns to ``main``."""
if args.command == "stop":
- sys.exit(cmd_stop(receipt=args.receipt) if args.receipt is not None else cmd_stop())
+ if args.receipt is not None:
+ sys.exit(cmd_stop(receipt=args.receipt))
+ if args.expect_runtime_id is not None:
+ sys.exit(cmd_stop(expect_runtime_id=args.expect_runtime_id))
+ sys.exit(cmd_stop())
if args.command == "start":
if _generation_downgrade_blocks("start", allow_downgrade=args.allow_downgrade):
sys.exit(1)
diff --git a/vibe/desktop_backends.py b/vibe/desktop_backends.py
index 649c66dc2..937000e15 100644
--- a/vibe/desktop_backends.py
+++ b/vibe/desktop_backends.py
@@ -4,20 +4,50 @@ from __future__ import annotations
import json
import logging
+import math
import os
import platform
+import re
import shutil
+import signal
import subprocess
import tempfile
+import threading
+import time
import uuid
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from pathlib import Path, PurePosixPath
from typing import Any
-from core.process_isolation import KILL_SIGNAL, isolated_subprocess_kwargs, signal_process_tree
+import psutil
+
+from config import paths
+from config.atomic_io import write_atomic
+from core.process_isolation import (
+ KILL_SIGNAL,
+ PROCESS_IDENTITY_ENV,
+ PersistedProcessIdentity,
+ capture_spawned_process_identity,
+ fingerprint_process_marker,
+ is_valid_worker_fingerprint,
+ isolated_subprocess_kwargs,
+ new_process_identity_marker,
+ process_group_exists,
+ processes_carrying_marker,
+ process_identity_from_payload,
+ reap_marked_processes,
+ reap_orphaned_process_tree,
+ serialize_process_identity,
+ signal_process_tree,
+)
from storage.lock import MigrationFileLock, MigrationLockTimeout
from vibe.desktop_runtime import (
+ DESKTOP_INSTALLER_OWNER_ENV,
+ DESKTOP_INSTALLER_ROLE,
+ DESKTOP_ROLE_ENV,
+ DESKTOP_RUNTIME_ID_ENV,
+ desktop_runtime_id,
private_desktop_backends_root,
private_desktop_node_bin,
private_desktop_npm_cli,
@@ -34,6 +64,11 @@ DESKTOP_BACKEND_LOCK_TIMEOUT_SECONDS = 30.0
DESKTOP_BACKEND_INSTALL_TIMEOUT_SECONDS = 300.0
DESKTOP_BACKEND_PROBE_TIMEOUT_SECONDS = 15.0
DESKTOP_BACKEND_PROCESS_DRAIN_TIMEOUT_SECONDS = 10.0
+# Per phase of stopping an installer tree. Two phases fit inside the grace a
+# managed stop gives the owning UI before it escalates to SIGKILL (5 s).
+DESKTOP_BACKEND_TERMINATE_TIMEOUT_SECONDS = 1.5
+DESKTOP_BACKEND_INSTALL_LABEL = "desktop backend install"
+INSTALL_RECORD_SCHEMA_VERSION = 1
@dataclass(frozen=True)
@@ -237,19 +272,13 @@ def install_desktop_backend(
backend_root = toolchain.backends_root / backend
_prepare_backend_root(toolchain.backends_root, backend_root)
- lock = MigrationFileLock(
- backend_root / ".install.lock",
- timeout_seconds=DESKTOP_BACKEND_LOCK_TIMEOUT_SECONDS,
- )
- try:
- lock.acquire()
- except MigrationLockTimeout as exc:
- raise DesktopBackendError(
- f"Another {backend} install is already running.",
- code="install_locked",
- ) from exc
+ lock = _claim_backend_root(backend_root, timeout_seconds=DESKTOP_BACKEND_LOCK_TIMEOUT_SECONDS)
staging = backend_root / f".staging-{uuid.uuid4().hex}"
+ # The lock says "no installer is working in this root". An installer tree
+ # that could not be shown gone may still be writing into staging, so both
+ # the lock and staging stay as they are until this process exits.
+ installer_undrained = False
try:
staging.mkdir(mode=0o700)
user_config = staging / "npm-user.conf"
@@ -271,6 +300,7 @@ def install_desktop_backend(
f"--registry={NPM_REGISTRY}",
spec.package,
]
+ logger.info("Installing desktop backend package %s", spec.package)
completed = _run_command(
command,
cwd=staging,
@@ -342,7 +372,8 @@ def install_desktop_backend(
path=str(published_executable),
output=output,
)
- except DesktopBackendError:
+ except DesktopBackendError as exc:
+ installer_undrained = exc.code == "install_drain_failed"
raise
except Exception as exc:
raise DesktopBackendError(
@@ -350,8 +381,17 @@ def install_desktop_backend(
code="desktop_install_failed",
) from exc
finally:
- _remove_staging_directory(staging, backend_root)
- lock.release()
+ if installer_undrained:
+ logger.error(
+ "Keeping %s held: a %s process tree could not be shown to have exited",
+ lock.lock_path,
+ DESKTOP_BACKEND_INSTALL_LABEL,
+ )
+ else:
+ # The record goes only with its staging, and both before the lock.
+ if _remove_staging_directory(staging, backend_root):
+ _forget_installer_record(_installer_record_path(staging))
+ lock.release()
def _prepare_backend_root(root: Path, backend_root: Path) -> None:
@@ -455,29 +495,472 @@ def _run_command(
env: Mapping[str, str],
timeout_seconds: float,
) -> subprocess.CompletedProcess[str]:
- logger.info("Installing desktop backend package %s", command[-1])
- process = subprocess.Popen(
- command,
- cwd=cwd,
- env=dict(env),
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- text=True,
- **isolated_subprocess_kwargs(),
+ owned = _spawn_owned_installer(command, cwd=cwd, env=env)
+ process = owned.process
+ try:
+ try:
+ stdout, stderr = process.communicate(timeout=timeout_seconds)
+ except subprocess.TimeoutExpired as exc:
+ signal_process_tree(process, KILL_SIGNAL, logger, DESKTOP_BACKEND_INSTALL_LABEL)
+ stdout, stderr = process.communicate(
+ timeout=DESKTOP_BACKEND_PROCESS_DRAIN_TIMEOUT_SECONDS,
+ )
+ raise DesktopBackendError(
+ "Desktop backend install timed out.",
+ code="install_timeout",
+ output=_bounded_output(stdout, stderr),
+ ) from exc
+ finally:
+ # npm exiting is not its tree exiting: anything it started is still
+ # in its process group, or at least still carries the marker.
+ if not _settle_owned_installer(owned):
+ raise DesktopBackendError(
+ "Desktop backend installer processes did not exit.",
+ code="install_drain_failed",
+ )
+ return subprocess.CompletedProcess(command, process.returncode, stdout, stderr)
+
+
+@dataclass
+class _OwnedInstaller:
+ """An installer tree this process started, and so must see gone."""
+
+ process: subprocess.Popen[str]
+ worker_fingerprint: str
+ identity: PersistedProcessIdentity | None
+ settled: bool = False
+
+
+# The owner-side registry. Its lock is held across spawn and registration, so
+# a drain that starts meanwhile waits and then sees the new tree too.
+_OWNED_INSTALLERS: dict[str, _OwnedInstaller] = {}
+_OWNED_INSTALLERS_LOCK = threading.RLock()
+_INSTALLERS_CLOSED = False
+
+
+_STAGING_NAME = re.compile(r"\.staging-[0-9a-f]{32}")
+
+
+def _installer_records_dir() -> Path:
+ return paths.get_runtime_dir() / "desktop-backend-installs"
+
+
+def _installer_record_path(staging: Path) -> Path:
+ return _installer_records_dir() / f"{staging.name.removeprefix('.staging-')}.json"
+
+
+def _write_installer_record(
+ record_path: Path,
+ *,
+ worker_fingerprint: str,
+ identity: PersistedProcessIdentity | None,
+ staging: Path,
+) -> None:
+ payload = {
+ "schema_version": INSTALL_RECORD_SCHEMA_VERSION,
+ "worker_fingerprint": worker_fingerprint,
+ "identity": None if identity is None else serialize_process_identity(identity),
+ "staging": str(staging),
+ }
+ write_atomic(record_path, json.dumps(payload, separators=(",", ":")))
+
+
+def _forget_installer_record(record_path: Path) -> None:
+ try:
+ record_path.unlink(missing_ok=True)
+ except OSError:
+ logger.warning("Could not remove %s record %s", DESKTOP_BACKEND_INSTALL_LABEL, record_path, exc_info=True)
+
+
+def _spawn_owned_installer(
+ command: list[str],
+ *,
+ cwd: Path,
+ env: Mapping[str, str],
+) -> _OwnedInstaller:
+ # ``cwd`` is the install's staging directory. Its record names it, and goes
+ # only with it: the install removes both, or a claim of the root does.
+ marker = new_process_identity_marker()
+ worker_fingerprint = fingerprint_process_marker(marker)
+ record_path = _installer_record_path(cwd)
+ child_env = dict(env)
+ child_env[PROCESS_IDENTITY_ENV] = marker
+ # Every member inherits these, so a process scan finds the whole tree and
+ # its owner without its record: the stops and the claim decide by them.
+ child_env[DESKTOP_ROLE_ENV] = DESKTOP_INSTALLER_ROLE
+ child_env[DESKTOP_INSTALLER_OWNER_ENV] = _installer_owner()
+ runtime_id = desktop_runtime_id()
+ if runtime_id is not None:
+ child_env[DESKTOP_RUNTIME_ID_ENV] = runtime_id
+ with _OWNED_INSTALLERS_LOCK:
+ if _INSTALLERS_CLOSED:
+ raise DesktopBackendError(
+ "Avibe is shutting down; the desktop backend install was not started.",
+ code="install_shutting_down",
+ )
+ # Recorded before the spawn, so a stopper can find the tree by its
+ # marker even if this process dies before it learns the pid.
+ _write_installer_record(record_path, worker_fingerprint=worker_fingerprint, identity=None, staging=cwd)
+ process = subprocess.Popen(
+ command,
+ cwd=cwd,
+ env=child_env,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ **isolated_subprocess_kwargs(),
+ )
+ identity = capture_spawned_process_identity(process.pid, marker)
+ owned = _OwnedInstaller(process, worker_fingerprint, identity)
+ _OWNED_INSTALLERS[worker_fingerprint] = owned
+ if identity is not None:
+ try:
+ _write_installer_record(
+ record_path, worker_fingerprint=worker_fingerprint, identity=identity, staging=cwd
+ )
+ except OSError:
+ # The marker alone still finds the tree; only the pid is lost.
+ logger.warning("Could not record the %s pid=%s", DESKTOP_BACKEND_INSTALL_LABEL, process.pid, exc_info=True)
+ return owned
+
+
+def _stop_owned_installer_leader(process: subprocess.Popen[str]) -> bool:
+ """Stop and reap the installer this process spawned, through its own handle.
+
+ The handle is what makes this exact: ``wait`` reaps the leader, so the reap
+ that follows never mistakes an unreaped zombie for a live member.
+ """
+
+ for sig in (signal.SIGTERM, KILL_SIGNAL):
+ if process.poll() is not None:
+ return True
+ signal_process_tree(process, sig, logger, DESKTOP_BACKEND_INSTALL_LABEL)
+ try:
+ process.wait(timeout=DESKTOP_BACKEND_TERMINATE_TIMEOUT_SECONDS)
+ except subprocess.TimeoutExpired:
+ continue
+ return True
+ return process.poll() is not None
+
+
+def _await_installer_group_exit(identity: PersistedProcessIdentity | None) -> None:
+ """Give members the group signal reached their phase to exit and be reaped.
+
+ Until its reaper collects it, an exited member still occupies the group
+ and no longer shows its marker, which would leave the reap unable to
+ confirm the group is ours or gone.
+ """
+
+ if identity is None or os.name == "nt":
+ return
+ deadline = time.monotonic() + DESKTOP_BACKEND_TERMINATE_TIMEOUT_SECONDS
+ while process_group_exists(identity.pid, logger, DESKTOP_BACKEND_INSTALL_LABEL):
+ if time.monotonic() >= deadline:
+ return
+ time.sleep(0.05)
+
+
+def _reap_installer_tree(
+ worker_fingerprint: str,
+ identity: PersistedProcessIdentity | None,
+) -> bool:
+ """Stop whatever is left of an installer tree; True once it is shown gone."""
+
+ outcomes = []
+ if identity is not None:
+ outcomes.append(
+ reap_orphaned_process_tree(logger, DESKTOP_BACKEND_INSTALL_LABEL, expected_identity=identity)
+ )
+ # The marker is the authority: it also finds members that left the group.
+ outcomes.append(
+ reap_marked_processes(
+ logger,
+ DESKTOP_BACKEND_INSTALL_LABEL,
+ worker_fingerprint=worker_fingerprint,
+ terminate_timeout=DESKTOP_BACKEND_TERMINATE_TIMEOUT_SECONDS,
+ )
)
+ return "unconfirmed" not in outcomes
+
+
+def _settle_owned_installer(owned: _OwnedInstaller) -> bool:
+ with _OWNED_INSTALLERS_LOCK:
+ if owned.settled:
+ return True
+ try:
+ gone = _stop_owned_installer_leader(owned.process)
+ if gone:
+ _await_installer_group_exit(owned.identity)
+ gone = _reap_installer_tree(owned.worker_fingerprint, owned.identity)
+ except Exception:
+ logger.exception("Unexpected error stopping the %s tree", DESKTOP_BACKEND_INSTALL_LABEL)
+ gone = False
+ if not gone:
+ logger.error(
+ "Could not show the %s tree pid=%s exited; keeping its record",
+ DESKTOP_BACKEND_INSTALL_LABEL,
+ owned.process.pid,
+ )
+ return False
+ owned.settled = True
+ _OWNED_INSTALLERS.pop(owned.worker_fingerprint, None)
+ return True
+
+
+def drain_desktop_backend_installs() -> bool:
+ """Stop every installer tree this process started, before it exits.
+
+ For the owning process's shutdown: after this call it starts no new
+ installer. Returns False when a tree could not be shown gone. Its durable
+ record stays either way until the install removes its staging; one left
+ behind is cleared by the next claim of its backend root.
+ """
+
+ global _INSTALLERS_CLOSED
+ with _OWNED_INSTALLERS_LOCK:
+ _INSTALLERS_CLOSED = True
+ owned = list(_OWNED_INSTALLERS.values())
+ drained = True
+ for installer in owned:
+ drained = _settle_owned_installer(installer) and drained
+ return drained
+
+
+@dataclass(frozen=True)
+class _InstallerRecord:
+ path: Path
+ worker_fingerprint: str
+ identity: PersistedProcessIdentity | None
+ staging: Path
+
+ @property
+ def backend_root(self) -> Path:
+ return self.staging.parent
+
+
+def _recorded_staging(value: Any) -> Path | None:
+ """The staging directory a record names, if an install could have made it.
+
+ Only ``<backends root>/<backend>/.staging-<hex>`` qualifies, so removing a
+ recorded staging directory can never reach a release, a descriptor or
+ anything outside a backend root.
+ """
+
+ if not isinstance(value, str) or os.path.normpath(value) != value:
+ return None
+ staging = Path(value)
+ if not staging.is_absolute() or not _STAGING_NAME.fullmatch(staging.name):
+ return None
+ return staging if staging.parent.name in BACKEND_SPECS else None
+
+
+def _read_installer_record(record_path: Path) -> _InstallerRecord | None:
+ """The record at ``record_path``, or ``None`` when what it holds is invalid.
+
+ Raises ``OSError`` when it cannot be read: such a record is unknown, not
+ invalid, and must not be discarded.
+ """
+
+ text = record_path.read_bytes()
+ try:
+ payload = json.loads(text.decode("utf-8"))
+ except (UnicodeError, json.JSONDecodeError):
+ return None
+ if not isinstance(payload, dict) or payload.get("schema_version") != INSTALL_RECORD_SCHEMA_VERSION:
+ return None
+ worker_fingerprint = payload.get("worker_fingerprint")
+ raw_identity = payload.get("identity")
+ staging = _recorded_staging(payload.get("staging"))
+ if not is_valid_worker_fingerprint(worker_fingerprint) or staging is None:
+ return None
+ identity = None
+ if raw_identity is not None:
+ identity = process_identity_from_payload(
+ raw_identity,
+ raw_identity.get("pid") if isinstance(raw_identity, dict) else None,
+ )
+ if identity is None or identity.worker_fingerprint != worker_fingerprint:
+ return None
+ return _InstallerRecord(record_path, worker_fingerprint, identity, staging)
+
+
+def _installer_records() -> list[_InstallerRecord]:
+ """Every valid installer record, for a claim to clear the staging it names.
+
+ Raises ``OSError`` when the directory or a record in it cannot be read:
+ the listing is then unknown and nothing is discarded. A record proven
+ invalid is discarded only once every record has been read.
+ """
+
+ try:
+ with os.scandir(_installer_records_dir()) as entries:
+ record_paths = sorted(Path(entry.path) for entry in entries if entry.name.endswith(".json"))
+ except FileNotFoundError:
+ # No install has recorded anything yet.
+ return []
+ records: list[_InstallerRecord] = []
+ invalid: list[Path] = []
+ for record_path in record_paths:
+ try:
+ record = _read_installer_record(record_path)
+ except FileNotFoundError:
+ # Its install finished after the listing.
+ continue
+ if record is None:
+ invalid.append(record_path)
+ else:
+ records.append(record)
+ for record_path in invalid:
+ # Nothing in it can identify a process, so it authorises nothing.
+ logger.warning("Discarding invalid %s record %s", DESKTOP_BACKEND_INSTALL_LABEL, record_path)
+ _forget_installer_record(record_path)
+ return records
+
+
+def _clear_abandoned_install(record: _InstallerRecord) -> bool:
+ """Reap a recorded installer tree, then remove its staging and its record.
+
+ True once the tree is shown gone. The record stays until its staging is.
+ """
+
+ try:
+ gone = _reap_installer_tree(record.worker_fingerprint, record.identity)
+ except Exception:
+ logger.exception("Unexpected error stopping the %s recorded in %s", DESKTOP_BACKEND_INSTALL_LABEL, record.path)
+ gone = False
+ if not gone:
+ logger.error("Could not stop the %s recorded in %s", DESKTOP_BACKEND_INSTALL_LABEL, record.path)
+ return False
+ if _remove_staging_directory(record.staging, record.backend_root):
+ _forget_installer_record(record.path)
+ return True
+
+
+def _installer_owner() -> str:
+ from vibe import runtime
+
+ started_at = runtime.process_create_time(os.getpid())
+ if started_at is None:
+ raise DesktopBackendError(
+ "Avibe could not identify itself as the owner of a desktop backend install.",
+ code="desktop_install_failed",
+ )
+ return f"{os.getpid()}:{started_at!r}"
+
+
+def _installer_owner_gone(owner: str, runtime_id: str | None) -> bool | None:
+ """Whether the process named by the owner value of a ``runtime_id`` tree has exited.
+
+ The owner is gone when its pid is not alive, and alive while that pid
+ keeps its create time. macOS can shift the create time psutil shows for a
+ process that keeps running, so another one alone proves nothing: the pid
+ was reused only when the process now holding it is readable and is not a
+ UI of that Runtime, as every owner is. ``None`` when the value is
+ malformed, or the create time differs and the process cannot be read.
+ """
+
+ from vibe import runtime
+
+ pid_text, _, started_text = owner.partition(":")
+ try:
+ pid, started_at = int(pid_text), float(started_text)
+ except ValueError:
+ return None
+ if pid <= 0 or not math.isfinite(started_at):
+ return None
+ if not runtime.pid_alive(pid):
+ return True
+ if runtime.process_create_time(pid) == started_at:
+ return False
+ is_ui = runtime.is_desktop_ui(pid, runtime_id)
+ return None if is_ui is None else not is_ui
+
+
+def reap_abandoned_desktop_backend_installs(runtime_id: str | None = None) -> bool:
+ """Stop every installer tree of a Runtime whose owner has exited.
+
+ ``runtime_id`` defaults to this process's. Installs run only in the UI,
+ which drains its own trees as it exits; one killed first leaves its tree
+ running. A process scan finds such trees by the role and Runtime id every
+ member inherits, and each tree names its owner, so no record or pidfile
+ decides, whichever process asks. Staging and records stay for the next
+ claim of their backend root. Returns False when a tree could not be shown
+ gone, or its owner could not be told alive or gone.
+ """
+
+ if runtime_id is None:
+ runtime_id = desktop_runtime_id()
+ abandoned: set[str] = set()
+ for process in processes_carrying_marker(
+ fingerprint_process_marker(DESKTOP_INSTALLER_ROLE),
+ marker_env=DESKTOP_ROLE_ENV,
+ ):
+ try:
+ env = process.environ()
+ except psutil.NoSuchProcess:
+ continue
+ except (psutil.Error, OSError):
+ logger.error("Could not inspect the %s pid=%s", DESKTOP_BACKEND_INSTALL_LABEL, process.pid, exc_info=True)
+ return False
+ if desktop_runtime_id(env) != runtime_id:
+ continue
+ marker = env.get(PROCESS_IDENTITY_ENV, "")
+ if not marker or not marker.isascii():
+ logger.error("The %s pid=%s carries no identity marker", DESKTOP_BACKEND_INSTALL_LABEL, process.pid)
+ return False
+ gone = _installer_owner_gone(env.get(DESKTOP_INSTALLER_OWNER_ENV, ""), runtime_id)
+ if gone is None:
+ logger.error("Could not tell whether the owner of the %s pid=%s is alive", DESKTOP_BACKEND_INSTALL_LABEL, process.pid)
+ return False
+ if gone:
+ abandoned.add(fingerprint_process_marker(marker))
+ # By its marker, which also finds members started since the scan.
+ return all([_reap_installer_tree(fingerprint, None) for fingerprint in sorted(abandoned)])
+
+
+def _claim_backend_root(backend_root: Path, *, timeout_seconds: float) -> MigrationFileLock:
+ """Take ``backend_root``'s install lock, with no abandoned installer left in it.
+
+ Every acquisition of ``.install.lock`` goes through here. Liveness comes
+ from the process scan: every abandoned installer tree of this Runtime is
+ reaped first. An install holds the lock from before its record exists
+ until after it has removed its staging and then its record, so a record
+ for this root seen under the lock names an install whose owner died
+ first; its tree is reaped by its marker and its staging removed. When the
+ records cannot be listed or read, nothing is removed; then, or when a
+ tree cannot be shown gone, the lock is released and ``install_locked``
+ raised.
+ """
+
+ lock = MigrationFileLock(backend_root / ".install.lock", timeout_seconds=timeout_seconds)
+ try:
+ lock.acquire()
+ except MigrationLockTimeout as exc:
+ raise DesktopBackendError(
+ f"Another {backend_root.name} install is already running.",
+ code="install_locked",
+ ) from exc
try:
- stdout, stderr = process.communicate(timeout=timeout_seconds)
- except subprocess.TimeoutExpired as exc:
- signal_process_tree(process, KILL_SIGNAL, logger, "desktop backend install")
- stdout, stderr = process.communicate(
- timeout=DESKTOP_BACKEND_PROCESS_DRAIN_TIMEOUT_SECONDS,
+ records = [record for record in _installer_records() if record.backend_root == backend_root]
+ settled = reap_abandoned_desktop_backend_installs() and all(
+ [_clear_abandoned_install(record) for record in records]
)
+ except OSError as exc:
+ lock.release()
raise DesktopBackendError(
- "Desktop backend install timed out.",
- code="install_timeout",
- output=_bounded_output(stdout, stderr),
+ f"The {backend_root.name} install records could not be read.",
+ code="install_locked",
) from exc
- return subprocess.CompletedProcess(command, process.returncode, stdout, stderr)
+ except BaseException:
+ lock.release()
+ raise
+ if not settled:
+ lock.release()
+ raise DesktopBackendError(
+ f"A previous {backend_root.name} install could not be shown to have stopped.",
+ code="install_locked",
+ )
+ return lock
def _installed_package_version(package_dir: Path, expected_package: str) -> str:
@@ -606,16 +1089,24 @@ def _verify_backend_executable(
f"Installed {backend} executable failed validation.",
code="invalid_executable",
)
+ # Spawned as an installer, so the probe is owned, recorded and scanned
+ # like the npm tree before it: no stop or drain can miss it.
try:
- result = subprocess.run(
+ result = _run_command(
[str(executable), "--version"],
cwd=root,
- env=dict(env),
- capture_output=True,
- text=True,
- timeout=DESKTOP_BACKEND_PROBE_TIMEOUT_SECONDS,
+ env=env,
+ timeout_seconds=DESKTOP_BACKEND_PROBE_TIMEOUT_SECONDS,
)
- except (OSError, subprocess.TimeoutExpired) as exc:
+ except DesktopBackendError as exc:
+ if exc.code != "install_timeout":
+ raise
+ raise DesktopBackendError(
+ f"Installed {backend} executable did not report a version in time.",
+ code="executable_probe_failed",
+ output=exc.output,
+ ) from exc
+ except OSError as exc:
raise DesktopBackendError(
f"Installed {backend} executable could not be started.",
code="executable_probe_failed",
@@ -757,11 +1248,13 @@ def _write_descriptor_bytes(path: Path, encoded: bytes) -> None:
temporary.unlink(missing_ok=True)
-def _remove_staging_directory(staging: Path, backend_root: Path) -> None:
+def _remove_staging_directory(staging: Path, backend_root: Path) -> bool:
+ """Remove ``staging`` if it lies under ``backend_root``; True once it is gone."""
+
try:
staging.relative_to(backend_root)
except ValueError:
- return
+ return False
try:
if staging.is_symlink():
staging.unlink(missing_ok=True)
@@ -769,6 +1262,7 @@ def _remove_staging_directory(staging: Path, backend_root: Path) -> None:
shutil.rmtree(staging)
except OSError:
logger.warning("Failed to remove desktop backend staging directory %s", staging)
+ return not os.path.lexists(staging)
def _remove_internal_directory(path: Path, root: Path) -> None:
diff --git a/vibe/desktop_runtime.py b/vibe/desktop_runtime.py
index bed638001..c1a773445 100644
--- a/vibe/desktop_runtime.py
+++ b/vibe/desktop_runtime.py
@@ -23,6 +23,19 @@ DESKTOP_RUNTIME_ROOT_ENV = "AVIBE_DESKTOP_RUNTIME_ROOT"
DESKTOP_NODE_BIN_ENV = "VIBE_SHOW_RUNTIME_NODE_BIN"
DESKTOP_NPM_CLI_ENV = "AVIBE_DESKTOP_NPM_CLI"
DESKTOP_BACKENDS_ROOT_ENV = "AVIBE_DESKTOP_BACKENDS_ROOT"
+# Every process a backend install starts carries this, so a process scan tells
+# an installer tree from the other programs that carry the Runtime id.
+DESKTOP_ROLE_ENV = "AVIBE_DESKTOP_ROLE"
+DESKTOP_INSTALLER_ROLE = "installer"
+# The OpenCode server manager stamps the server. The agent work it runs inherits
+# the stamp too, so the stamp alone names no role.
+DESKTOP_OPENCODE_ROLE = "opencode"
+# ``<pid>:<create time>`` of the UI that started an installer tree, which every
+# member inherits: the tree is abandoned once that UI is gone. A pid that is not
+# alive is gone. macOS can shift the create time of a running process, so a
+# different one is a reused pid only when the process holding it is readable and
+# is not a UI of the tree's Runtime; when it cannot be read, nobody can tell.
+DESKTOP_INSTALLER_OWNER_ENV = "AVIBE_DESKTOP_INSTALLER_OWNER"
START_RECEIPT_PREFIX = "@avibe-start-receipt:"
START_RECEIPT_TIME_TOLERANCE_MS = 2.0
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 953772d11..3838788aa 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -842,7 +842,10 @@
"checkUpdate": "Updates are delivered with the Avibe desktop app.",
"upgrade": "This Runtime is managed by the Avibe desktop app. Update the app to update Avibe.",
"apiUpgrade": "This Runtime is managed by the Avibe desktop app.",
- "backendUpgrade": "This Codex backend belongs to an older Avibe desktop Runtime and cannot be updated in place. Reopen the current desktop app to install it privately."
+ "backendUpgrade": "This Codex backend belongs to an older Avibe desktop Runtime and cannot be updated in place. Reopen the current desktop app to install it privately.",
+ "handoverRefused": "Refused to stop the superseded desktop-managed Avibe Runtime: {reason}",
+ "handoverFailed": "Failed to stop the superseded desktop-managed Avibe Runtime: {part}",
+ "handoverForeignUi": "A UI server that is not the superseded desktop-managed Avibe Runtime's is still running."
},
"agentInstall": {
"installFailed": "Could not install {backend}.",
@@ -1073,6 +1076,14 @@
"repairExplicitCommandFailed": "The Show Runtime command from VIBE_SHOW_RUNTIME_BIN could not start: {reason}. Fix or remove the override, then rerun Doctor.",
"repairPrepareFailed": "Show Runtime preparation failed: {detail}",
"repairLegacyArchiveUnavailable": "The packaged Show Runtime manifest is unavailable and the legacy upstream archive URL has no release asset. Upgrade or reinstall the official Avibe package, or remove stale runtime source overrides."
+ },
+ "stop": {
+ "opencodeStopped": "OpenCode server stopped",
+ "serviceFailed": "ERROR: Avibe service did not stop; preserving pidfile and aborting.",
+ "uiFailed": "ERROR: Avibe UI did not stop; preserving pidfile and aborting.",
+ "installerFailed": "ERROR: Desktop backend installer processes did not stop.",
+ "opencodeFailed": "ERROR: The OpenCode server this Runtime started did not stop.",
+ "unknownFailed": "ERROR: A process this Runtime started could not be identified and was left running."
}
},
"doctor": {
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index a315a3fd4..937d0b3ab 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -842,7 +842,10 @@
"checkUpdate": "更新由 Avibe 桌面应用统一提供。",
"upgrade": "此 Runtime 由 Avibe 桌面应用管理。请更新桌面应用来更新 Avibe。",
"apiUpgrade": "此 Runtime 由 Avibe 桌面应用管理。",
- "backendUpgrade": "此 Codex 后端属于旧版 Avibe 桌面 Runtime,无法原地更新。请重新打开当前桌面应用,将其安装为私有后端。"
+ "backendUpgrade": "此 Codex 后端属于旧版 Avibe 桌面 Runtime,无法原地更新。请重新打开当前桌面应用,将其安装为私有后端。",
+ "handoverRefused": "已拒绝停止被取代的桌面托管 Avibe Runtime:{reason}",
+ "handoverFailed": "未能停止被取代的桌面托管 Avibe Runtime:{part}",
+ "handoverForeignUi": "仍有一个不属于被取代的桌面托管 Avibe Runtime 的 UI 服务在运行。"
},
"agentInstall": {
"installFailed": "无法安装 {backend}。",
@@ -1073,6 +1076,14 @@
"repairPostVerificationFailed": "Show Runtime 准备已完成,但无法验证是否可启动:{detail}",
"repairPrepareFailed": "Show Runtime 准备失败:{detail}",
"repairLegacyArchiveUnavailable": "打包的 Show Runtime 清单不可用,旧版上游归档地址也没有发布资产。请升级或重新安装官方 Avibe 软件包,或移除过期的 runtime 来源覆盖配置。"
+ },
+ "stop": {
+ "opencodeStopped": "OpenCode 服务已停止",
+ "serviceFailed": "错误:Avibe 服务未能停止;已保留 pidfile 并中止。",
+ "uiFailed": "错误:Avibe UI 未能停止;已保留 pidfile 并中止。",
+ "installerFailed": "错误:桌面后端安装进程未能停止。",
+ "opencodeFailed": "错误:此 Runtime 启动的 OpenCode 服务未能停止。",
+ "unknownFailed": "错误:此 Runtime 启动的一个进程无法识别,已保留运行。"
}
},
"doctor": {
diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.py
index 6d1c829fe..9e045a91e 100644
--- a/vibe/restart_supervisor.py
+++ b/vibe/restart_supervisor.py
@@ -365,6 +365,14 @@ def _run_restart_job(
mark_duration("stop_runtime_seconds", stop_runtime_started_at)
if restart_ui and ui_pid and ui_stopped is False and runtime.pid_alive(ui_pid):
return fail(f"UI pid {ui_pid} did not stop", 2, started_at=restart_started_at)
+ if restart_ui:
+ from vibe.desktop_backends import reap_abandoned_desktop_backend_installs
+
+ # The UI owns backend installs. One killed before it drained them
+ # leaves the installer tree running, and the successor must not
+ # start while it is.
+ if not reap_abandoned_desktop_backend_installs():
+ return fail("desktop backend installer processes did not stop", 2, started_at=restart_started_at)
if stopped is False:
remaining_service_pids = _remaining_service_pids_after_stop()
if remaining_service_pids:
diff --git a/vibe/runtime.py b/vibe/runtime.py
index 6d52140e0..051080e0c 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -1,4 +1,5 @@
import calendar
+import errno
import getpass
import ipaddress
import json
@@ -17,6 +18,7 @@ import urllib.request
import uuid
from dataclasses import dataclass
from datetime import datetime, timezone
+from enum import Enum
from pathlib import Path
from typing import Callable, NamedTuple
@@ -33,7 +35,7 @@ from config.v2_config import (
SlackConfig,
V2Config,
)
-from core.process_isolation import isolated_subprocess_kwargs
+from core.process_isolation import fingerprint_process_marker, isolated_subprocess_kwargs, processes_carrying_marker
from vibe.log_sink import RUNTIME_LOG_MAX_BYTES, RUNTIME_LOG_RETAIN_BYTES
@@ -306,21 +308,32 @@ def _windows_lock_byte(lock_file, mode: int) -> None:
lock_file.seek(0)
-def _try_lock_file(lock_file) -> bool:
- if os.name == "nt":
- import msvcrt
+# What a non-blocking lock attempt fails with when another handle holds the lock.
+_LOCK_HELD_ERRNOS = frozenset({errno.EACCES, errno.EDEADLK} if os.name == "nt" else {errno.EAGAIN, errno.EWOULDBLOCK})
+
+
+def _take_lock_file(lock_file) -> bool:
+ """False when another handle holds the lock; raises ``OSError`` when the attempt itself failed."""
+
+ try:
+ if os.name == "nt":
+ import msvcrt
- try:
_windows_lock_byte(lock_file, msvcrt.LK_NBLCK)
- return True
- except OSError:
+ else:
+ import fcntl
+
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError as exc:
+ if exc.errno in _LOCK_HELD_ERRNOS:
return False
+ raise
+ return True
- import fcntl
+def _try_lock_file(lock_file) -> bool:
try:
- fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
- return True
+ return _take_lock_file(lock_file)
except OSError:
return False
@@ -1293,7 +1306,8 @@ def spawn_background(
"""
def hand_over(process: subprocess.Popen) -> None:
- pid_path.write_text(str(process.pid), encoding="utf-8")
+ # A reader never sees a half-written record: a full stop acts on it.
+ write_atomic(Path(pid_path), str(process.pid))
if start_info is not None:
start_info.capture(process.pid, reused=False)
@@ -2316,11 +2330,15 @@ def wait_for_ui_server(host: str, port: int, timeout: float = 5.0) -> bool:
return ui_server_healthy(host, port)
+def _is_ui_server_command(command: str) -> bool:
+ return "vibe.ui_server" in command and "run_ui_server" in command
+
+
def _pid_matches_ui_server(pid: int) -> bool:
command = get_process_command(pid)
if not command:
return False
- return "vibe.ui_server" in command and "run_ui_server" in command
+ return _is_ui_server_command(command)
def ui_pid_file_points_to_running_ui(pid_path: Path | None = None) -> bool:
@@ -2525,3 +2543,350 @@ def stop_ui(timings: dict[str, float | bool] | None = None, *, stop_remote_acces
timings["stop_ui_process_seconds"] = _rounded_seconds(time.monotonic() - ui_started_at)
timings["stop_ui_seconds"] = _rounded_seconds(time.monotonic() - started_at)
return bool(ui_stopped and remote_access_stopped)
+
+
+class DesktopRuntimePresence(Enum):
+ """Whether the desktop Runtime a scoped stop names is running.
+
+ ``MATCH`` comes from the process scan: a service, UI, backend installer
+ or OpenCode server carrying the id is running. With none running, the
+ service lock decides without its record being read: free is ``ABSENT``,
+ held is ``MISMATCH`` (the holder is not a service of this Runtime), and a
+ lock that cannot be probed is ``UNKNOWN``. The desktop host mirrors these
+ as Mine, Absent, Foreign and Unknown.
+ """
+
+ ABSENT = "absent"
+ MATCH = "match"
+ MISMATCH = "mismatch"
+ UNKNOWN = "unknown"
+
+
+class DesktopRuntimeStopOutcome(Enum):
+ """What a scoped stop left behind, decided by the rescan after it."""
+
+ NOT_OURS = "not_ours"
+ STOPPED = "stopped"
+ FAILED = "failed"
+
+
+_DESKTOP_STOP_REFUSALS = {
+ DesktopRuntimePresence.MISMATCH: "service_runtime_id_mismatch",
+ DesktopRuntimePresence.UNKNOWN: "service_identity_unavailable",
+}
+# A process carrying the id whose command line cannot be read may hold any
+# role, so it is never signalled and never counted as stopped.
+_UNKNOWN_DESKTOP_ROLE = "unknown"
+
+
+@dataclass(frozen=True)
+class DesktopRuntimeProcess:
+ """A process carrying the id: ``role`` is ``service``, ``ui``, ``installer``,
+ ``opencode``, ``unknown``, or ``None`` for any other program."""
+
+ pid: int
+ role: str | None
+ name: str
+
+
+@dataclass(frozen=True)
+class _ScannedDesktopProcess:
+ process: psutil.Process
+ report: DesktopRuntimeProcess
+ # This stop or one of its ancestors: never signalled.
+ lineage: bool
+
+
+@dataclass(frozen=True)
+class DesktopRuntimeStopResult:
+ """What a stop scoped to one desktop Runtime did.
+
+ ``refusal`` is set when nothing was signalled. ``remaining`` names the
+ role processes still carrying the id after the stop, and ``left_running``
+ the other programs carrying it, which the stop never signals.
+ """
+
+ refusal: str | None = None
+ remaining: tuple[DesktopRuntimeProcess, ...] = ()
+ left_running: tuple[DesktopRuntimeProcess, ...] = ()
+ opencode_stopped: bool = False
+
+ @property
+ def failure(self) -> str | None:
+ """The first part that did not stop: ``service``, ``ui``, ``installer``, ``opencode`` or ``unknown``."""
+
+ roles = {process.role for process in self.remaining}
+ for part in ("service", "ui", "installer", "opencode", _UNKNOWN_DESKTOP_ROLE):
+ if part in roles:
+ return part
+ return None
+
+ @property
+ def outcome(self) -> DesktopRuntimeStopOutcome:
+ if self.refusal is not None:
+ return DesktopRuntimeStopOutcome.NOT_OURS
+ if self.failure is not None:
+ return DesktopRuntimeStopOutcome.FAILED
+ return DesktopRuntimeStopOutcome.STOPPED
+
+
+# A scan classifies every process carrying the id, and an agent's command line
+# is arbitrary text, so each role is the exact argv shape Avibe launches it with.
+# Only the arguments Avibe writes decide: the program is whatever interpreter,
+# configured executable or shim runs them.
+_UI_SERVER_PAYLOAD = "from vibe.ui_server import run_ui_server;"
+
+
+def _is_ui_server_argv(argv: list[str]) -> bool:
+ # `start_ui` and the UI restart run `<python> -c "from vibe.ui_server import run_ui_server; ..."`.
+ return len(argv) >= 3 and argv[1] == "-c" and argv[2].startswith(_UI_SERVER_PAYLOAD)
+
+
+def _is_opencode_serve_argv(argv: list[str]) -> bool:
+ # The server manager runs `<agents.opencode.cli_path> serve --hostname=... --port=...`;
+ # a shim or wrapper runs it with its own program in front. Those arguments
+ # are common to servers, so they decide only for a process the manager stamped.
+ return (
+ len(argv) >= 4
+ and argv[-3] == "serve"
+ and argv[-2].startswith("--hostname=")
+ and argv[-1].startswith("--port=")
+ )
+
+
+def _is_desktop_service_command(command: str, cwd: str | None) -> bool:
+ # The bundle runs vibe/service_main.py. Its argv names the service even
+ # after an update has replaced or moved the files it started from.
+ try:
+ entry = _service_entry_arg_from_argv(shlex.split(command, posix=(os.name != "nt")))
+ except ValueError:
+ entry = None
+ if entry is not None:
+ path = Path(entry.strip("\"'"))
+ if path.name == "service_main.py" and path.parent.name == "vibe":
+ return True
+ return _command_looks_like_service_entry(command, cwd=cwd)
+
+
+def _own_lineage() -> frozenset[int]:
+ """This process and its ancestors: started by the desktop host, they carry the id too."""
+
+ lineage = {os.getpid(), os.getppid()}
+ try:
+ lineage.update(parent.pid for parent in psutil.Process().parents())
+ except psutil.Error:
+ logger.warning("Could not read every ancestor of this stop", exc_info=True)
+ return frozenset(lineage)
+
+
+def _desktop_process_gone(process: psutil.Process) -> bool:
+ try:
+ # is_running() compares the birth time psutil read at the scan, so a
+ # pid reused since then reads as gone, never as the scanned process.
+ return not process.is_running() or process.status() == psutil.STATUS_ZOMBIE
+ except psutil.NoSuchProcess:
+ return True
+ except psutil.Error:
+ return False
+
+
+def _desktop_process_role(process: psutil.Process) -> str | None:
+ """Raises ``psutil.NoSuchProcess`` for a process that has exited."""
+
+ from vibe.desktop_runtime import DESKTOP_INSTALLER_ROLE, DESKTOP_OPENCODE_ROLE, DESKTOP_ROLE_ENV
+
+ try:
+ stamped_role = process.environ().get(DESKTOP_ROLE_ENV)
+ # Every member of a backend install tree inherits the role, whatever
+ # program it runs.
+ if stamped_role == DESKTOP_INSTALLER_ROLE:
+ return "installer"
+ argv = [str(part) for part in process.cmdline()]
+ except psutil.NoSuchProcess:
+ raise
+ except (psutil.Error, OSError):
+ stamped_role = None
+ argv = []
+ command = shlex.join(argv)
+ if not command:
+ if _desktop_process_gone(process):
+ raise psutil.NoSuchProcess(process.pid)
+ return _UNKNOWN_DESKTOP_ROLE
+ if _is_desktop_service_command(command, _process_cwd(process)):
+ return "service"
+ if _is_ui_server_argv(argv):
+ return "ui"
+ if stamped_role == DESKTOP_OPENCODE_ROLE and _is_opencode_serve_argv(argv):
+ return "opencode"
+ return None
+
+
+def is_desktop_ui(pid: int, runtime_id: str | None) -> bool | None:
+ """Whether ``pid`` runs a UI carrying ``runtime_id``, or no Runtime id when that is ``None``.
+
+ A scan knows a UI by the same launch shape. ``None`` when the process
+ cannot be read; a process that has exited is no UI.
+ """
+
+ from vibe.desktop_runtime import desktop_runtime_id
+
+ try:
+ process = psutil.Process(pid)
+ role = _desktop_process_role(process)
+ if role != "ui":
+ return None if role == _UNKNOWN_DESKTOP_ROLE else False
+ return desktop_runtime_id(process.environ()) == runtime_id
+ except psutil.NoSuchProcess:
+ return False
+ except (psutil.Error, OSError):
+ return None
+
+
+def _scan_desktop_runtime(fingerprint: str, lineage: frozenset[int]) -> list[_ScannedDesktopProcess]:
+ """This user's processes carrying the id, by role, each with its scan handle."""
+
+ from vibe.desktop_runtime import DESKTOP_RUNTIME_ID_ENV
+
+ scanned: list[_ScannedDesktopProcess] = []
+ for process in processes_carrying_marker(fingerprint, marker_env=DESKTOP_RUNTIME_ID_ENV):
+ try:
+ role = _desktop_process_role(process)
+ except psutil.NoSuchProcess:
+ continue
+ try:
+ name = process.name()
+ except psutil.Error:
+ name = ""
+ report = DesktopRuntimeProcess(pid=process.pid, role=role, name=name)
+ scanned.append(_ScannedDesktopProcess(process, report, process.pid in lineage))
+ return scanned
+
+
+def desktop_service_lock_presence(while_absent: Callable[[], None] | None = None) -> DesktopRuntimePresence:
+ """With no role process carrying the id, whether anything else holds the service lock.
+
+ ``while_absent`` runs holding the free lock, so no service can take it,
+ and so publish its status, until it returns.
+ """
+
+ try:
+ lock_path = get_service_lock_path()
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
+ lock_file = lock_path.open("a+", encoding="utf-8")
+ except OSError:
+ logger.warning("Could not probe the service instance lock", exc_info=True)
+ return DesktopRuntimePresence.UNKNOWN
+ with lock_file:
+ # Only another holder is a mismatch; a lock call that failed says nothing.
+ try:
+ taken = _take_lock_file(lock_file)
+ except OSError:
+ logger.warning("Could not probe the service instance lock", exc_info=True)
+ return DesktopRuntimePresence.UNKNOWN
+ if not taken:
+ return DesktopRuntimePresence.MISMATCH
+ try:
+ if while_absent is not None:
+ while_absent()
+ finally:
+ _unlock_file(lock_file)
+ return DesktopRuntimePresence.ABSENT
+
+
+def _stop_desktop_processes(processes: list[psutil.Process], timeout: float = 5) -> None:
+ """Stop ``processes`` gracefully, then forcefully, through the handles the scan returned.
+
+ ``is_running()`` holds right before every signal, and psutil itself
+ refuses to signal a handle whose pid has been reused since the scan.
+ """
+
+ phases = (None,) if os.name == "nt" else (signal.SIGTERM, signal.SIGKILL)
+ alive = list(processes)
+ for sig in phases:
+ for process in alive:
+ if _desktop_process_gone(process):
+ continue
+ try:
+ if sig is None:
+ logger.info("Terminating desktop Runtime pid=%s", process.pid)
+ process.terminate()
+ else:
+ if sig == signal.SIGTERM:
+ write_shutdown_intent(process.pid, signum=signal.SIGTERM, reason="stop_pid")
+ logger.info("Sending managed %s to desktop Runtime pid=%s", signal.Signals(sig).name, process.pid)
+ process.send_signal(sig)
+ except psutil.NoSuchProcess:
+ continue
+ except (psutil.Error, OSError):
+ logger.warning("Failed to signal desktop Runtime pid=%s", process.pid, exc_info=True)
+ deadline = time.monotonic() + timeout
+ while True:
+ alive = [process for process in alive if not _desktop_process_gone(process)]
+ if not alive or time.monotonic() >= deadline:
+ break
+ time.sleep(0.1)
+ if not alive:
+ return
+ logger.error("Desktop Runtime processes did not exit: %s", [process.pid for process in alive])
+
+
+def stop_desktop_runtime(runtime_id: str) -> DesktopRuntimeStopResult:
+ """Stop only what the desktop Runtime ``runtime_id`` started.
+
+ Discovery is one scan of this user's processes for the id they inherited
+ in ``AVIBE_DESKTOP_RUNTIME_ID``; no pidfile or record is read. This stop
+ and its ancestors carry the id when the desktop host started it and are
+ never signalled. Service processes stop first, then the UI, each through
+ the handle the scan returned; then every backend installer tree of this
+ Runtime whose owning UI has exited; then its OpenCode server. A rescan
+ decides the outcome. Installer staging and records stay for the next
+ claim of their backend root.
+
+ Other programs carrying the id, such as agent CLIs and the tunnel
+ connector, are reported and left running. With no role process carrying
+ the id, a held service lock refuses the stop and nothing is signalled.
+
+ Role classification guards against accidental collisions, not mimicry.
+ An agent process already runs with the user's full authority and could
+ signal the service itself, so a process deliberately shaped like a role is
+ not a boundary this scan defends. Every descendant of the service inherits
+ every variable the service carries, so no inherited marker separates the
+ service from its agent tasks: the service is known by its launch shape and
+ the id alone. A process carrying the id that runs a file ending in
+ ``vibe/service_main.py`` is therefore stopped with the Runtime it belongs to.
+ """
+
+ from vibe.desktop_runtime import DESKTOP_RUNTIME_ID_ENV, desktop_runtime_id
+
+ if desktop_runtime_id({DESKTOP_RUNTIME_ID_ENV: runtime_id}) != runtime_id:
+ return DesktopRuntimeStopResult(refusal="invalid_runtime_id")
+ fingerprint = fingerprint_process_marker(runtime_id)
+ lineage = _own_lineage()
+ found = _scan_desktop_runtime(fingerprint, lineage)
+ if any(entry.report.role is not None for entry in found):
+ presence = DesktopRuntimePresence.MATCH
+ else:
+ presence = desktop_service_lock_presence()
+ refusal = _DESKTOP_STOP_REFUSALS.get(presence)
+ if refusal is not None:
+ return DesktopRuntimeStopResult(refusal=refusal)
+
+ def targets(role: str) -> list[psutil.Process]:
+ return [entry.process for entry in found if entry.report.role == role and not entry.lineage]
+
+ with _SERVICE_LOCK:
+ _stop_desktop_processes(targets("service"))
+ _stop_desktop_processes(targets("ui"))
+ from vibe.desktop_backends import reap_abandoned_desktop_backend_installs
+
+ # A tree whose owner is still alive stays, and the rescan reports it.
+ reap_abandoned_desktop_backend_installs(runtime_id)
+ opencode = targets("opencode")
+ _stop_desktop_processes(opencode)
+
+ left = _scan_desktop_runtime(fingerprint, lineage)
+ return DesktopRuntimeStopResult(
+ remaining=tuple(entry.report for entry in left if entry.report.role is not None),
+ left_running=tuple(entry.report for entry in left if entry.report.role is None and not entry.lineage),
+ opencode_stopped=any(_desktop_process_gone(process) for process in opencode),
+ )
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index e57b25fca..a477a6d83 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -16835,6 +16835,38 @@ app.add_event_handler("shutdown", _stop_startup_dependency_reconcile)
app.add_event_handler("shutdown", stop_show_runtime_on_shutdown)
+def drain_desktop_backend_installs_on_shutdown() -> None:
+ """Stop the backend installer trees this UI started, so none outlives it."""
+
+ from vibe.desktop_backends import drain_desktop_backend_installs
+
+ try:
+ drained = drain_desktop_backend_installs()
+ except Exception:
+ logger.error("Failed to drain desktop backend installs on shutdown", exc_info=True)
+ return
+ if not drained:
+ logger.error("Desktop backend installer processes are still running at shutdown")
+
+
+# A stop signal reaches handle_exit first; uvicorn then waits for open
+# connections before running lifespan shutdown, and a managed stop escalates to
+# SIGKILL well before a long-lived stream closes. Exits that set should_exit
+# directly still pass through lifespan shutdown.
+app.add_event_handler("shutdown", drain_desktop_backend_installs_on_shutdown)
+
+
+def _create_ui_server(config):
+ import uvicorn
+
+ class _UIServer(uvicorn.Server):
+ def handle_exit(self, sig, frame) -> None:
+ super().handle_exit(sig, frame)
+ drain_desktop_backend_installs_on_shutdown()
+
+ return _UIServer(config)
+
+
# cloudflared holds idle origin connections in a pool for up to
# --proxy-keepalive-timeout (default 1m30s) and reuses them for later requests.
# uvicorn's own default is 5s, so the origin closes connections the tunnel still
@@ -16918,7 +16950,7 @@ def run_ui_server(host: str, port: int) -> None:
timeout_keep_alive=_UI_KEEPALIVE_TIMEOUT_SECONDS,
)
bound_sockets = _bind_ui_sockets(host, port)
- _server = uvicorn.Server(uvicorn_config)
+ _server = _create_ui_server(uvicorn_config)
# Reconcile remote_access in the background so cloudflared download/
# connector start does not block /health and the rest of the UI
# from coming up after restart/reload.