Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(desktop): start, stop and restart act only on the caller's own Runtime (#2280)
Call White4206c07dbf51
diff --git a/docs/CLI.md b/docs/CLI.mdindex 50056bcf6..48ccda8db 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -68,6 +68,7 @@ vibe start --allow-downgrade- With `--no-open-browser`, keeps the service/UI lifecycle the same but does not launch a system browser window- **Preserves running processes** — Use `vibe restart` when you need an explicit restart- Refuses to run an install older than the last activated one, for example an old `vibe` earlier on `PATH`. The error names both versions and the launcher to run instead; `--allow-downgrade` runs the older build on purpose. The desktop app only warns.+- Started by the desktop app, reuses or replaces only a service and Web UI of that app's own Runtime. If another Avibe is running here, it exits with status 3, says so, and leaves that Avibe running.### `vibe stop`@@ -81,6 +82,7 @@ vibe stop- Stops the main service- Stops the web UI server- **Terminates OpenCode server** — Use this when you need to restart OpenCode+- Run from inside a desktop app's Runtime (for example, by an agent it started), stops only that Runtime. If the Avibe running here is another one, it stops nothing, explains why, and exits with status 3.### `vibe restart`@@ -97,6 +99,7 @@ vibe restart --allow-downgrade- Terminates the OpenCode server- With `--delay-seconds N`, schedules the restart `N` seconds in the future so an active conversation can receive its reply before the restart lands. Prefer this form when an agent is triggering the restart from inside Slack, Discord, Telegram, Lark/Feishu, or WeChat.- Refuses, like `vibe start`, to restart onto an install older than the last activated one unless you pass `--allow-downgrade`+- Run from inside a desktop app's Runtime, restarts only that Runtime; otherwise it stops nothing, explains why, and exits with status 3. A restart from the Web UI shows the same refusal instead of restarting.### `vibe status`diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.mdindex 0505679c3..7593cb2cf 100644--- a/docs/CLI_ZH.md+++ b/docs/CLI_ZH.md@@ -66,6 +66,7 @@ vibe start --allow-downgrade- 使用 `--no-open-browser` 时,服务和 Web UI 的启动/复用逻辑不变,但不会额外拉起系统浏览器窗口- **保留已运行的进程** — 需要明确重启时请使用 `vibe restart`- `vibe start` 和 `vibe restart` 会拒绝运行比最近一次激活更旧的安装,例如 `PATH` 中更靠前的旧 `vibe`。错误信息会写明两个版本以及应改用的启动器;如确实要运行旧版本,请加 `--allow-downgrade`。桌面应用只给出警告。+- 由桌面应用启动时,只复用或替换该应用自己 Runtime 的主服务和 Web UI。如果这里运行的是另一个 Avibe,会说明原因并以状态码 3 退出,那个 Avibe 继续运行。### `vibe stop`@@ -79,6 +80,7 @@ vibe stop- 停止主服务- 停止 Web UI 服务器- **终止 OpenCode 服务器** — 当你需要重启 OpenCode 时使用此命令+- 在桌面应用的 Runtime 内运行时(例如由它启动的 Agent),`vibe stop` 和 `vibe restart` 只作用于该 Runtime。如果这里运行的是另一个 Avibe,则什么都不停止,说明原因并以状态码 3 退出;在 Web UI 中重启也会显示同样的拒绝,而不会重启。### `vibe status`diff --git a/docs/plans/desktop-runtime-scoped-stop.md b/docs/plans/desktop-runtime-scoped-stop.mdindex 767b1ad6d..3f74e6d3b 100644--- a/docs/plans/desktop-runtime-scoped-stop.md+++ b/docs/plans/desktop-runtime-scoped-stop.md@@ -1,7 +1,8 @@# Desktop Runtime scoped stop and installer ownershipRefs #2135, #2131. PR 2a is the Python half; PR 2b is the desktop host and-removes the startup receipt from both sides.+removes the startup receipt from both sides; PR 3 makes the start, plain stop+and restart boundaries claim only by provenance.## Outcome and boundaries@@ -9,8 +10,10 @@ 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 itsbundle started, and asks Python to stop only processes that carry that id. Thescoped stop reads no file: no pidfile, lock record or installer record decides-what is signalled. `/ready` and `/internal/health` are unchanged, and so is-plain `vibe stop`. The startup receipt (`@avibe-start-receipt:` and+what is signalled. `/ready` and `/internal/health` are unchanged. Plain+`vibe stop` is unchanged for a caller without desktop provenance; a desktop+caller refuses it for any Runtime but its own (see "Start and restart claim").+The startup receipt (`@avibe-start-receipt:` and`vibe stop --receipt`) is gone: provenance is the Runtime id, not a receipt thehost has to keep.@@ -107,16 +110,64 @@ controller whose health names another desktop Runtime id:- without `--hand-over` it exits 3 and leaves that Runtime running;- with it, it calls the same `runtime.stop_desktop_runtime` with that observed- id, and exits 3 if the stop is refused and 2 if it fails;-- it also exits 3 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.+ id, and exits 3 if the stop is refused and 2 if it fails.++Whatever is still running afterwards is not the superseded Runtime's; the start+claim below decides whether this start may reuse or replace it.Exit 3 means this start did not take the home over; exit 2 means the supersededRuntime may be left partly running. `runtime.stop_desktop_runtime` never stopsthe tunnel connector, so the successor adopts it. These errors go through`vibe/i18n/` (`desktopRuntime.handover*`).+## Start and restart claim (PR 3)++No actor stops, reuses, adopts or replaces a Runtime it has no provenance over.+A refusal says why, exits 3, and leaves everything running.++**Start claim.** With `E = desktop_runtime_id()` of the caller's environment,+`vibe start` claims a service or UI only when the process carries+`AVIBE_DESKTOP_RUNTIME_ID == E` (`runtime.claim_desktop_runtime_process`).+The claim points are every reuse return of `_resolve_service_pid` and the pid+`wait_for_service_ready` ends with (`claim_ready_service`), and the UI reuse or+replace decision in `start_ui`. There, under `E`, a UI pid whose command line+cannot be read is refused rather than taken for a stale pidfile; a readable UI+command is claimed by its environment; a readable non-UI command is still a+stale pidfile. A refusal raises `DesktopRuntimeClaimRefused(part, reason)`,+`cmd_start` rolls back only what it spawned, and it exits 3 with+`desktopRuntime.claimRefused`. A start without `E` claims as before.++**Provenance.** `desktop_runtime.desktop_caller_provenance()` is the set of the+caller's environment id and the id of the private tree its interpreter runs+from. The tree id is read from the install marker `.avibe-runtime.json` that+the host writes at the tree root (`write_marker` in+`desktop/runtime-host/src/private_runtime.rs`): the nearest marker within three+directories above the resolved interpreter decides, and it counts only when its+`archive_sha256` is 64 lowercase hex and its relative `python_entrypoint`+resolves back to that interpreter. Anything else, including a marker further+up, names no tree. Against a service carrying Runtime B:++| Caller env | Caller tree | Result |+| --- | --- | --- |+| A | A | refuse |+| B | B | allow |+| B | A | refuse |+| none | A | refuse |+| none | B | allow |+| none | none | as before |++With provenance, nothing running proceeds; a service, an extra service process+or a live UI pidfile pid that cannot be read, or that carries another id or+none, refuses. The check (`runtime.desktop_provenance_refusal`) runs on plain+`vibe stop` (exit 3, `desktopRuntime.stopRefused`), in `vibe restart` before+anything is scheduled (exit 3, `desktopRuntime.restartRefused`), and in the+restart job before it stops anything or carries the desktop identity (rc 3,+status `failed`, error `restart refused: …`). The Web restart (`/api/control`+restart, 409 `restart_refused`) and the config-save fallback restart+(`platform_runtime.restart_code = restart_refused`) ask first, so the status is+never set to `restarting` for a restart that will not happen, and the UI shows+the refusal.+## Backend installer ownership (#2131)- The UI process that starts an installer owns its tree. npm and the installed@@ -239,11 +290,23 @@ the tunnel connector, so the successor adopts it. These errors go through- argparse usage errors also exit 2, so a `vibe start` too old to know`--hand-over` reads as a handover that may have left the predecessor partlyrunning. The bundled launcher is always the same version, so this cannot- happen, and the reading fails closed. No other `vibe start` path exits 2 or 3.-- A `vibe restart` or plain `vibe stop` run by a process a superseded Runtime- left running still acts on the Controller unscoped, because its desktop- identity was stripped with its old root. Claiming by the caller's own id- belongs at the start and restart boundary, tracked in #2135 for PR 3.+ happen, and the reading fails closed. Besides the handover, only a start+ claim refusal exits 3: another Runtime serves this home and the start did+ not replace it, which the host reads as the same `HandoverRefused` →+ `runtime_ownership_lost`. No other `vibe start` path exits 2 or 3.+- The Web `/api/control` stop is not checked for provenance: it is the person+ at this Runtime's own Workbench stopping the service it serves.+- The Web restart and config-save pre-checks are check-then-act. A Runtime+ that replaces this one in between is still refused by the restart job+ (rc 3). The job records that failure in its own restart status and, as+ after any failed restart job, the runtime state stays `restarting`; the Web+ UI's fast poll stops after 45 s.+- A Runtime that lost its desktop identity (a terminal restart on a TEST+ prerelease before the G15 carry-over, or a deliberate manual run) is adopted+ as external by the host and managed from a terminal as before. Telling it+ from a non-desktop Avibe would need `/ready` to report its root and version.+- A caller whose environment and tree name two different ids acts for+ neither.- A role process in the stop's own lineage is never signalled and fails thestop; a program without a role in the lineage is not listed.- The scoped stop path reads no file: no pidfile, lock record or installer@@ -261,13 +324,6 @@ the tunnel connector, so the successor adopts it. These errors go throughcode 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 itspid and parent pid, with a warning; a role process of this Runtime further upthe chain could then be signalled.@@ -312,5 +368,10 @@ spawn error → `Unrunnable`. The host never stops a predecessor itself.offers "Delete Anyway" or "Keep Files".- B8, Stop and Quit: offered only while the last presence is `Mine`. A refusalshows `runtime_ownership_lost`; a failure shows `runtime_stop_failed`.-- `Unknown` → launch relies on the start boundary, tracked in- https://github.com/avibe-bot/avibe/issues/2135#issuecomment-5877263657.+- `Unknown` → launch relies on the start claim: the start reuses or replaces+ only processes carrying this bundle's id and otherwise exits 3.+- A failed return to the bootstrap page after a Stop or a failed removal+ keeps no lifecycle owner (`lib.rs` `recover_after_runtime_removal_failure`).+ On these paths it fails only when the event loop has exited, so no owner is+ left to restore; see+ https://github.com/avibe-bot/avibe/pull/2269#discussion_r4131364951.diff --git a/tests/conftest.py b/tests/conftest.pyindex 84b6a20e2..479a2a915 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -67,6 +67,18 @@ REAL_USER_HOME = Path.home()_SQLITE_DEFAULT_STATE_MODULES: dict[Path, bool] = {}+def pytest_configure(config):+ # A desktop caller is also whoever runs from a private tree's interpreter,+ # which no environment clearing undoes: every stop and restart under test+ # would act as that live Runtime.+ from vibe.desktop_runtime import _desktop_tree_runtime_id++ if _desktop_tree_runtime_id(sys.executable) is not None:+ raise pytest.UsageError(+ f"{sys.executable} is a desktop Runtime's private interpreter; run the tests with another Python"+ )++def _module_uses_default_sqlite_state(request: pytest.FixtureRequest) -> bool:"""Avoid creating a migration template for tests that never use SQLite state."""@@ -230,6 +242,11 @@ def _isolate_vibe_remote_home(request, tmp_path, monkeypatch):"AVIBE_SKILL_XDG_CONFIG_HOME","AVIBE_BUILTIN_SKILLS_ROOT","AVIBE_BUILTIN_SKILLS_SNAPSHOT_ID",+ # A pytest started from a desktop Runtime's terminal would otherwise+ # act as that Runtime, and every stop, restart and start refuses or+ # claims by its id.+ "AVIBE_DESKTOP_RUNTIME_ID",+ "AVIBE_DESKTOP_RUNTIME_ROOT",):monkeypatch.delenv(name, raising=False)isolated_home = tmp_path / "home"diff --git a/tests/test_desktop_backends.py b/tests/test_desktop_backends.pyindex 011497905..6b4d78e92 100644--- a/tests/test_desktop_backends.py+++ b/tests/test_desktop_backends.py@@ -499,10 +499,10 @@ def quiet_stop(monkeypatch):# 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, "stop_service", lambda **kwargs: 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)+ monkeypatch.setattr(cli, "_stop_opencode_server", lambda *args: False)statuses: list[tuple] = []monkeypatch.setattr(cli, "_write_status", lambda *args, **kwargs: statuses.append(args))return cli, statuses@@ -567,18 +567,21 @@ def test_stop_reaps_the_tree_of_an_owner_that_died_before_draining(monkeypatch,@pytest.mark.skipif(os.name == "nt", reason="POSIX process groups")@pytest.mark.parametrize("failing", ["service", "ui"])def test_a_full_stop_that_fails_still_reaps_the_tree_of_a_dead_owner(- monkeypatch, installer_tree, quiet_stop, failing+ monkeypatch, installer_tree, quiet_stop, children, failing):from vibe import runtimeenv, wait_for_tree = installer_treecli, statuses = quiet_stoppids = _start_killed_owner(env, wait_for_tree)- # The stop reports this half as still running.+ # The stop reports this half, a process of the caller's own Runtime, as+ # still running.+ children.append(subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]))+ running = children[-1].pidif failing == "service":- monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda include_starting=True: os.getpid())+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda include_starting=True: running)else:- config_paths.get_runtime_ui_pid_path().write_text(str(os.getpid()), encoding="utf-8")+ config_paths.get_runtime_ui_pid_path().write_text(str(running), encoding="utf-8")monkeypatch.setattr(runtime, "stop_ui", lambda **kwargs: False)assert cli.cmd_stop() == 2@@ -609,11 +612,11 @@ def test_the_tree_of_a_live_owner_stays_whatever_the_ui_pidfile_says(else:seen_at_start: list[list[int]] = []- def start(start_ui=True):+ def start(start_ui=True, **kwargs):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, "_stop_service_for_restart", lambda runtime_ids: (True, 0.0))monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", start)diff --git a/tests/test_desktop_runtime.py b/tests/test_desktop_runtime.pyindex 5ce848bdb..7db07278c 100644--- a/tests/test_desktop_runtime.py+++ b/tests/test_desktop_runtime.py@@ -3,7 +3,9 @@ from __future__ import annotationsimport asyncioimport ioimport json+import osimport socket+import sysimport threadingimport urllib.errorfrom pathlib import Path@@ -23,6 +25,7 @@ from config.v2_config import ()from vibe import cli, internal_client, runtimefrom vibe.desktop_runtime import (+ desktop_caller_provenance,desktop_runtime_id,desktop_endpoint_payload,desktop_origin,@@ -144,6 +147,185 @@ def test_desktop_runtime_id_accepts_only_lowercase_sha256():assert desktop_runtime_id({}) is None+def _host_marker(runtime_id: str) -> dict[str, object]:+ """The marker the desktop host writes into a private tree it unpacks.++ `write_marker` in desktop/runtime-host/src/private_runtime.rs serialises+ `RuntimeBundleManifest` into `.avibe-runtime.json` at the tree root,+ `<install root>/<runtime_version>/<archive_sha256[:16]>/`. Field names and+ values are copied from that struct and its `write_bundle` test fixture.+ """++ return {+ "schema_version": 2,+ "runtime_version": "3.0.0-test",+ "os": "macos",+ "arch": "aarch64",+ "archive": "runtime.zip",+ "archive_sha256": runtime_id,+ "archive_size": 1234,+ "unpacked_size": 21,+ "entry_count": 3,+ "tree_sha256": "d" * 64,+ "python_entrypoint": "python/bin/python3",+ "node_entrypoint": "tools/bin/node",+ "npm_entrypoint": "tools/npm/bin/npm-cli.js",+ "python_distribution": {"url": "https://example.invalid/python", "sha256": "a" * 64},+ "node_distribution": {"url": "https://example.invalid/node", "sha256": "b" * 64},+ "npm_version": "10.9.8",+ "avibe_wheel": {"name": "avibe_os-3.0.0-py3-none-any.whl", "sha256": "c" * 64},+ }+++def _write_marker(path: Path, marker: object) -> None:+ # serde_json::to_vec writes compact JSON.+ path.write_text(json.dumps(marker, separators=(",", ":")), encoding="utf-8")+++def desktop_tree(tmp_path):+ """An unpacked private tree: `python/bin/python3` links to `python3.12`, as in the bundle."""++ if os.name == "nt":+ pytest.skip("the POSIX tree layout links python3 to python3.12")+ runtime_id = "e" * 64+ root = tmp_path / "install" / "3.0.0-test" / runtime_id[:16]+ bin_dir = root / "python" / "bin"+ bin_dir.mkdir(parents=True)+ (bin_dir / "python3.12").write_bytes(b"")+ (bin_dir / "python3").symlink_to("python3.12")+ _write_marker(root / ".avibe-runtime.json", _host_marker(runtime_id))+ return SimpleNamespace(root=root, interpreter=bin_dir / "python3", runtime_id=runtime_id)++[email protected]("name", ["python3", "python3.12"])+def test_a_desktop_tree_interpreter_acts_for_its_tree(desktop_tree, monkeypatch, name):+ monkeypatch.setattr(sys, "executable", str(desktop_tree.interpreter.parent / name))+ other = "f" * 64++ assert desktop_caller_provenance() == {desktop_tree.runtime_id}+ monkeypatch.setenv("AVIBE_DESKTOP_RUNTIME_ID", desktop_tree.runtime_id)+ assert desktop_caller_provenance() == {desktop_tree.runtime_id}+ monkeypatch.setenv("AVIBE_DESKTOP_RUNTIME_ID", other)+ assert desktop_caller_provenance() == {desktop_tree.runtime_id, other}+++def test_a_caller_outside_any_tree_has_only_its_env_provenance(desktop_tree, monkeypatch, tmp_path):+ outside = tmp_path / "venv" / "bin" / "python3"+ outside.parent.mkdir(parents=True)+ outside.write_bytes(b"")+ monkeypatch.setattr(sys, "executable", str(outside))++ assert desktop_caller_provenance() == frozenset()+ monkeypatch.setenv("AVIBE_DESKTOP_RUNTIME_ID", desktop_tree.runtime_id)+ assert desktop_caller_provenance() == {desktop_tree.runtime_id}+++# Every interpreter layout a desktop bundle ships, from the bundle's own sources.+_BUNDLE_PYTHON_ENTRYPOINTS = sorted(+ {+ target["python_entrypoint"]+ for target in json.loads(+ (Path(__file__).resolve().parents[1] / "desktop" / "runtime-sources.json").read_text(encoding="utf-8")+ )["targets"].values()+ }+)++[email protected](params=_BUNDLE_PYTHON_ENTRYPOINTS)+def bundle_tree(request, tmp_path):+ """A private tree with the interpreter where one of the bundle targets puts it."""++ runtime_id = "e" * 64+ root = tmp_path / "install" / "3.0.0-test" / runtime_id[:16]+ interpreter = root / request.param+ interpreter.parent.mkdir(parents=True)+ interpreter.write_bytes(b"")+ _write_marker(root / ".avibe-runtime.json", {**_host_marker(runtime_id), "python_entrypoint": request.param})+ return SimpleNamespace(root=root, interpreter=interpreter, entrypoint=request.param, runtime_id=runtime_id)+++def test_every_bundle_interpreter_acts_for_its_tree(bundle_tree, monkeypatch):+ monkeypatch.setattr(sys, "executable", str(bundle_tree.interpreter))++ assert desktop_caller_provenance() == {bundle_tree.runtime_id}+++def test_a_marker_above_the_tree_root_names_no_tree(bundle_tree, monkeypatch):+ # Its entrypoint does lead to this interpreter, but from above the root.+ (bundle_tree.root / ".avibe-runtime.json").unlink()+ stray = {**_host_marker("f" * 64), "python_entrypoint": f"{bundle_tree.root.name}/{bundle_tree.entrypoint}"}+ _write_marker(bundle_tree.root.parent / ".avibe-runtime.json", stray)+ monkeypatch.setattr(sys, "executable", str(bundle_tree.interpreter))++ assert desktop_caller_provenance() == frozenset()+++def _replace_marker(**fields):+ def write(root: Path, interpreter: Path, runtime_id: str) -> None:+ _write_marker(root / ".avibe-runtime.json", {**_host_marker(runtime_id), **fields})++ return write+++def _absolute_entrypoint(root: Path, interpreter: Path, runtime_id: str) -> None:+ _replace_marker(python_entrypoint=str(interpreter))(root, interpreter, runtime_id)+++def _missing_field(name: str):+ def write(root: Path, interpreter: Path, runtime_id: str) -> None:+ marker = _host_marker(runtime_id)+ del marker[name]+ _write_marker(root / ".avibe-runtime.json", marker)++ return write+++def _raw_marker(raw: bytes):+ def write(root: Path, interpreter: Path, runtime_id: str) -> None:+ (root / ".avibe-runtime.json").write_bytes(raw)++ return write+++def _oversized_marker(root: Path, interpreter: Path, runtime_id: str) -> None:+ raw = json.dumps(_host_marker(runtime_id)).encode()+ (root / ".avibe-runtime.json").write_bytes(raw + b" " * (32 * 1024 + 1 - len(raw)))+++def _symlinked_marker(root: Path, interpreter: Path, runtime_id: str) -> None:+ elsewhere = root.parent / "marker.json"+ _write_marker(elsewhere, _host_marker(runtime_id))+ (root / ".avibe-runtime.json").symlink_to(elsewhere)+++ "write_marker",+ [+ pytest.param(_replace_marker(archive_sha256="E" * 64), id="uppercase-id"),+ pytest.param(_replace_marker(archive_sha256="e" * 63), id="short-id"),+ pytest.param(_missing_field("archive_sha256"), id="no-id"),+ pytest.param(_missing_field("python_entrypoint"), id="no-entrypoint"),+ pytest.param(_replace_marker(python_entrypoint=["python", "bin", "python3"]), id="entrypoint-not-a-string"),+ pytest.param(_replace_marker(python_entrypoint="tools/bin/node"), id="entrypoint-elsewhere"),+ pytest.param(_absolute_entrypoint, id="absolute-entrypoint"),+ pytest.param(_raw_marker(b"[]"), id="not-an-object"),+ pytest.param(_raw_marker(b"{not json"), id="not-json"),+ pytest.param(_oversized_marker, id="oversized"),+ pytest.param(_symlinked_marker, id="symlinked"),+ ],+)+def test_an_invalid_root_marker_names_no_tree(desktop_tree, monkeypatch, write_marker):+ marker = desktop_tree.root / ".avibe-runtime.json"+ marker.unlink()+ write_marker(desktop_tree.root, desktop_tree.interpreter, desktop_tree.runtime_id)+ # A marker further up does not stand in for the broken one.+ _write_marker(desktop_tree.root.parent / ".avibe-runtime.json", _host_marker(desktop_tree.runtime_id))+ monkeypatch.setattr(sys, "executable", str(desktop_tree.interpreter))++ assert desktop_caller_provenance() == frozenset()++def test_private_desktop_runtime_path_is_confined_to_absolute_launcher_root(tmp_path):root = tmp_path / "runtime" / "3.1.0" / ("a" * 16)env = {"AVIBE_DESKTOP_RUNTIME_ROOT": str(root)}@@ -1212,7 +1394,7 @@ def test_cmd_start_reused_controller_starts_missing_ui_and_emits_untagged_ready(return Truemonkeypatch.setattr(cli.runtime, "wait_for_ui_server", wait_for_ui)- monkeypatch.setattr(cli.runtime, "stop_service", lambda: pytest.fail("reused Controller must survive"))+ monkeypatch.setattr(cli.runtime, "stop_service", lambda **kwargs: pytest.fail("reused Controller must survive"))monkeypatch.setattr(cli.runtime,"stop_ui",diff --git a/tests/test_desktop_runtime_stop.py b/tests/test_desktop_runtime_stop.pyindex 1cbe087b5..5aa726556 100644--- a/tests/test_desktop_runtime_stop.py+++ b/tests/test_desktop_runtime_stop.py@@ -1,4 +1,9 @@-"""``vibe stop --expect-runtime-id``: a stop that signals only the Runtime it scanned.+"""A desktop Runtime acts only on processes carrying its id.++``vibe stop --expect-runtime-id`` signals only the Runtime it scanned. A plain+stop or restart from a desktop caller, and a desktop start reusing what already+runs, claim only their own Runtime's processes and otherwise refuse, leaving+everything running.Targets are real child processes whose environment does or does not carry``AVIBE_DESKTOP_RUNTIME_ID`` and whose command line, or for a backend@@ -18,13 +23,16 @@ import signalimport subprocessimport sysfrom pathlib import Path+from types import SimpleNamespaceimport psutilimport pytestfrom config import pathsfrom config.v2_config import V2Config-from vibe import cli, desktop_backends, desktop_runtime, remote_access, runtime, ui_server+from tests.ui_server_test_helpers import csrf_headers+from vibe import cli, desktop_backends, desktop_runtime, remote_access, restart_supervisor, runtime, ui_server+from vibe.i18n import t as i18n_t# Random, so no process another test file started with a fixed id is ever in scope.RUNTIME_ID = secrets.token_hex(32)@@ -48,6 +56,9 @@ def bundle(tmp_path) -> Path:(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")+ # Next to the entry, as in a bundle: a service found by its record alone+ # is recognised by this.+ (root / "vibe" / "runtime.py").write_text("", 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@@ -526,8 +537,8 @@ def test_a_full_stop_keeps_a_surviving_opencode_server_non_fatal(spawn, stop_env# 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, "stop_service", lambda **kwargs: False)+ monkeypatch.setattr(runtime, "stop_ui", lambda **kwargs: False)monkeypatch.setattr(runtime, "extra_service_process_pids", lambda owner_pid=None: [])assert cli.cmd_stop() == 0@@ -535,3 +546,602 @@ def test_a_full_stop_keeps_a_surviving_opencode_server_non_fatal(spawn, stop_envassert stop_env["stop_pid"] == [opencode.pid]assert _alive(opencode)assert stop_env["status"] == [("stopped",)]+++def _service_lock_held_for(child: subprocess.Popen | None):+ """Hold the service lock with ``child`` as its recorded holder, as a running service does.++ With no ``child`` the lock is held and nothing names its holder.+ """++ 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)+ if child is not None:+ held.write(json.dumps({"pid": child.pid}))+ held.flush()+ paths.get_runtime_pid_path().write_text(str(child.pid), encoding="utf-8")+ yield+++def caller(monkeypatch, tmp_path):+ """Give this process a desktop provenance: the id in its environment, and the tree it runs from.++ Spawn children first: the tree's interpreter becomes ``sys.executable``.+ """++ paths.ensure_data_dirs()++ def _caller(env_id: str | None, root_id: str | None = None) -> None:+ if env_id is None:+ monkeypatch.delenv(desktop_runtime.DESKTOP_RUNTIME_ID_ENV, raising=False)+ else:+ monkeypatch.setenv(desktop_runtime.DESKTOP_RUNTIME_ID_ENV, env_id)+ if root_id is not None:+ root = tmp_path / "install" / "3.0.0" / root_id[:16]+ (root / "python" / "bin").mkdir(parents=True)+ (root / "python" / "bin" / "python3").write_bytes(b"")+ marker = {"archive_sha256": root_id, "python_entrypoint": "python/bin/python3"}+ (root / ".avibe-runtime.json").write_text(json.dumps(marker), encoding="utf-8")+ monkeypatch.setattr(sys, "executable", str(root / "python" / "bin" / "python3"))++ return _caller+++def running_runtime(spawn):+ """This Runtime's service holding the lock, and its UI on record."""++ paths.ensure_data_dirs()+ service = spawn(RUNTIME_ID)+ ui = spawn(RUNTIME_ID, "ui")+ paths.get_runtime_ui_pid_path().write_text(str(ui.pid), encoding="utf-8")+ with _service_lock_held_for(service):+ yield service, ui+++ ("env_id", "root_id", "refused"),+ [+ pytest.param(OTHER_ID, OTHER_ID, True, id="env-A-root-A"),+ pytest.param(RUNTIME_ID, RUNTIME_ID, False, id="env-B-root-B"),+ pytest.param(RUNTIME_ID, OTHER_ID, True, id="env-B-root-A"),+ pytest.param(None, OTHER_ID, True, id="root-A"),+ pytest.param(None, RUNTIME_ID, False, id="root-B"),+ pytest.param(None, None, False, id="no-provenance"),+ ],+)+def test_a_desktop_caller_acts_only_for_the_runtime_it_came_from(running_runtime, caller, env_id, root_id, refused):+ caller(env_id, root_id)++ refusal = runtime.desktop_provenance_refusal()++ if refused:+ assert (refusal.part, refusal.reason) == ("service", "runtime_id_mismatch")+ else:+ assert refusal is None+++ ("service_id", "ui_id", "include_ui", "expected"),+ [+ pytest.param(None, RUNTIME_ID, True, ("service", "runtime_id_mismatch"), id="id-less-service"),+ pytest.param(RUNTIME_ID, OTHER_ID, True, ("ui", "runtime_id_mismatch"), id="foreign-ui"),+ pytest.param(RUNTIME_ID, None, True, ("ui", "runtime_id_mismatch"), id="id-less-ui"),+ # A restart of the service alone leaves the UI where it is.+ pytest.param(RUNTIME_ID, OTHER_ID, False, None, id="service-scope-foreign-ui"),+ ],+)+def test_every_part_a_desktop_caller_would_act_on_must_be_its_own(+ spawn, caller, service_id, ui_id, include_ui, expected+):+ service = spawn(service_id)+ ui = spawn(ui_id, "ui")+ paths.get_runtime_ui_pid_path().write_text(str(ui.pid), encoding="utf-8")+ caller(RUNTIME_ID)++ with _service_lock_held_for(service):+ refusal = runtime.desktop_provenance_refusal(include_ui=include_ui)++ assert (None if refusal is None else (refusal.part, refusal.reason)) == expected+++def test_a_desktop_caller_that_cannot_read_the_service_refuses(running_runtime, caller, monkeypatch):+ caller(RUNTIME_ID)+ service, _ui = running_runtime+ real_environ = psutil.Process.environ++ def environ(process):+ if process.pid == service.pid:+ raise psutil.AccessDenied(process.pid)+ return real_environ(process)++ monkeypatch.setattr(psutil.Process, "environ", environ)++ refusal = runtime.desktop_provenance_refusal()++ assert (refusal.part, refusal.reason) == ("service", "identity_unavailable")+++def test_with_nothing_running_a_desktop_caller_may_proceed(caller):+ caller(OTHER_ID, OTHER_ID)++ assert runtime.desktop_provenance_refusal() is None+++def test_a_plain_stop_from_another_desktop_runtime_stops_nothing(running_runtime, caller, stop_env, capsys):+ caller(OTHER_ID)++ assert cli.cmd_stop() == 3++ assert _stderr_lines(capsys)[-1] == i18n_t(+ "desktopRuntime.stopRefused", "en", part="service", reason="runtime_id_mismatch"+ )+ 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 running_runtime)+++def test_a_plain_stop_refuses_while_nothing_names_the_service_lock_holder(spawn, caller, stop_env, capsys):+ # The UI and the tunnel connector serve whichever service holds the lock.+ ui = spawn(RUNTIME_ID, "ui")+ paths.get_runtime_ui_pid_path().write_text(str(ui.pid), encoding="utf-8")+ caller(RUNTIME_ID)++ with _service_lock_held_for(None):+ assert cli.cmd_stop() == 3++ assert _stderr_lines(capsys)[-1] == i18n_t(+ "desktopRuntime.stopRefused", "en", part="service", reason="identity_unavailable"+ )+ assert stop_env["signals"] == []+ assert stop_env["stop_pid"] == []+ assert stop_env["remote_access"] == []+ assert stop_env["status"] == []+ assert _alive(ui)++[email protected]("server_id", [RUNTIME_ID, OTHER_ID])+def test_a_plain_stop_stops_only_its_own_runtime_s_opencode_server(spawn, caller, stop_env, server_id):+ # The server record may still name one another Runtime's service started.+ server = spawn(server_id, "opencode")+ _opencode_pid_path().write_text(json.dumps({"pid": server.pid}), encoding="utf-8")+ caller(RUNTIME_ID)++ assert cli.cmd_stop() == 0++ assert stop_env["stop_pid"] == ([server.pid] if server_id == RUNTIME_ID else [])+ assert stop_env["status"] == [("stopped",)]+ assert _alive(server)++[email protected]("entry", ["stop", "restart-job"])+def test_a_stop_from_a_runtime_s_own_tree_reaps_its_abandoned_installers(spawn, caller, stop_env, monkeypatch, entry):+ # Only the interpreter names the Runtime; the environment names none.+ owner = spawn(RUNTIME_ID, "ui")+ installer = spawn(RUNTIME_ID, "installer", owner=owner)+ owner.kill()+ owner.wait(timeout=10)+ caller(None, RUNTIME_ID)++ if entry == "stop":+ assert cli.cmd_stop() == 0+ else:+ reaped_before_the_successor = []++ def start_runtime_processes(**kwargs):+ reaped_before_the_successor.append(_signalled(stop_env, installer))+ raise RuntimeError("the successor is not started here")++ monkeypatch.setattr(+ restart_supervisor, "_stop_runtime_for_restart", lambda **kwargs: (True, {}, 0.0, None, True, 0.0)+ )+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", start_runtime_processes)+ restart_supervisor._run_restart_job(job_id="jobreap", delay_seconds=0, vibe_path=None, trigger="test")+ assert reaped_before_the_successor == [True]++ assert (installer.pid, signal.SIGTERM) in stop_env["signals"]+++def test_a_plain_restart_from_another_desktop_runtime_schedules_nothing(+ running_runtime, caller, stop_env, capsys, monkeypatch+):+ monkeypatch.setattr(cli, "schedule_restart", lambda **kwargs: pytest.fail("no restart may be scheduled"))+ caller(None, OTHER_ID)++ assert cli.cmd_restart() == 3++ assert _stderr_lines(capsys)[-1] == i18n_t(+ "desktopRuntime.restartRefused", "en", part="service", reason="runtime_id_mismatch"+ )+ assert stop_env["signals"] == []+ assert all(_alive(child) for child in running_runtime)+++def test_a_restart_job_for_another_desktop_runtime_fails_before_stopping_anything(+ running_runtime, caller, stop_env, monkeypatch+):+ # The job acts on whatever runs when it starts, whoever scheduled it.+ monkeypatch.setattr(+ restart_supervisor, "_stop_runtime_for_restart", lambda **kwargs: pytest.fail("nothing may be stopped")+ )+ caller(OTHER_ID)++ rc = restart_supervisor._run_restart_job(job_id="jobrefused", delay_seconds=0, vibe_path=None, trigger="test")++ assert rc == 3+ status = runtime.read_json(runtime.get_restart_status_path())+ assert (status["ok"], status["state"]) == (False, "failed")+ assert status["error"].startswith("restart refused: ")+ assert stop_env["signals"] == []+ assert all(_alive(child) for child in running_runtime)+++def test_a_web_restart_from_another_desktop_runtime_is_refused_and_not_announced(running_runtime, caller, monkeypatch):+ monkeypatch.setattr(+ restart_supervisor, "schedule_restart", lambda **kwargs: pytest.fail("no restart may be scheduled")+ )+ runtime.write_status("running", "running", running_runtime[0].pid, running_runtime[1].pid)+ caller(OTHER_ID)+ client = ui_server.app.test_client()++ response = client.post("/api/control", json={"action": "restart"}, headers=csrf_headers(client))++ assert response.status_code == 409+ payload = response.get_json()+ assert (payload["code"], payload["part"], payload["reason"]) == (+ "restart_refused",+ "service",+ "runtime_id_mismatch",+ )+ assert runtime.read_status()["state"] == "running"+ assert all(_alive(child) for child in running_runtime)+++def test_a_config_restart_from_another_desktop_runtime_says_it_was_refused(running_runtime, caller, monkeypatch):+ monkeypatch.setattr(+ restart_supervisor, "schedule_restart", lambda **kwargs: pytest.fail("no restart may be scheduled")+ )+ runtime.write_status("running", "running", running_runtime[0].pid, running_runtime[1].pid)+ caller(OTHER_ID)++ result = ui_server._schedule_service_restart_for_config_fallback()++ assert (result["ok"], result["code"]) == (False, "restart_refused")+ assert runtime.read_status()["state"] == "running"+++ ("caller_id", "service_id", "outcome"),+ [+ pytest.param(RUNTIME_ID, OTHER_ID, "runtime_id_mismatch", id="foreign"),+ pytest.param(RUNTIME_ID, None, "runtime_id_mismatch", id="id-less"),+ pytest.param(RUNTIME_ID, RUNTIME_ID, "reused", id="own"),+ # A start that is not a desktop Runtime's reuses whatever runs, as it always has.+ pytest.param(None, OTHER_ID, "reused", id="no-desktop-id"),+ ],+)+def test_a_desktop_start_reuses_only_its_own_runtime_s_service(spawn, stop_env, caller, caller_id, service_id, outcome):+ service = spawn(service_id)+ caller(caller_id)+ info = runtime.ProcessStartInfo()++ with _service_lock_held_for(service):+ if outcome == "reused":+ assert runtime.start_service(wait_for_ready=False, start_info=info) == service.pid+ assert (info.pid, info.reused) == (service.pid, True)+ else:+ with pytest.raises(runtime.DesktopRuntimeClaimRefused) as refused:+ runtime.start_service(wait_for_ready=False, start_info=info)+ assert (refused.value.part, refused.value.reason) == ("service", outcome)+ assert info.pid is None++ assert stop_env["signals"] == []+ assert _alive(service)++[email protected]("record", ["missing", "corrupt", "another-program"])+def test_a_desktop_start_names_the_lock_holder_whatever_the_service_record_says(spawn, stop_env, caller, record):+ foreign = spawn(OTHER_ID)+ program = spawn(RUNTIME_ID, None)+ caller(RUNTIME_ID)++ with _service_lock_held_for(foreign):+ pid_path = paths.get_runtime_pid_path()+ if record == "missing":+ pid_path.unlink()+ elif record == "corrupt":+ pid_path.write_text("not a pid", encoding="utf-8")+ else:+ pid_path.write_text(str(program.pid), encoding="utf-8")+ with pytest.raises(runtime.DesktopRuntimeClaimRefused) as refused:+ runtime.start_service(wait_for_ready=False, start_info=runtime.ProcessStartInfo())++ assert (refused.value.part, refused.value.reason) == ("service", "runtime_id_mismatch")+ assert stop_env["signals"] == []+ assert _alive(foreign)++[email protected]("ui_id", [OTHER_ID, None, "unreadable"])+def test_a_desktop_start_neither_reuses_nor_replaces_a_ui_of_another_runtime(+ spawn, stop_env, caller, monkeypatch, ui_id+):+ ui = spawn(None if ui_id == "unreadable" else ui_id, "ui")+ paths.get_runtime_ui_pid_path().write_text(str(ui.pid), encoding="utf-8")+ if ui_id == "unreadable":+ real_command = runtime.get_process_command+ monkeypatch.setattr(runtime, "get_process_command", lambda pid: None if pid == ui.pid else real_command(pid))+ caller(RUNTIME_ID)++ with pytest.raises(runtime.DesktopRuntimeClaimRefused) as refused:+ runtime.start_ui("127.0.0.1", 5123, start_info=runtime.ProcessStartInfo())++ reason = "identity_unavailable" if ui_id == "unreadable" else "runtime_id_mismatch"+ assert (refused.value.part, refused.value.reason) == ("ui", reason)+ assert stop_env["signals"] == []+ assert stop_env["stop_pid"] == []+ assert _alive(ui)+++def _start_config(monkeypatch):+ config = SimpleNamespace(+ has_configured_platform_credentials=lambda: True,+ ui=SimpleNamespace(setup_host="127.0.0.1", setup_port=5123, open_browser=False),+ )+ monkeypatch.setattr(cli, "_ensure_config", lambda: config)+ monkeypatch.setattr(cli, "_handover_superseded_desktop_runtime", lambda **kwargs: 0)+ monkeypatch.setattr(runtime, "effective_ui_bind_host", lambda cfg: "127.0.0.1")+++ ("found", "part", "reason"),+ [+ pytest.param("service", "service", "runtime_id_mismatch", id="foreign-service"),+ pytest.param("lock-holder", "service", "identity_unavailable", id="unnamed-lock-holder"),+ pytest.param("ui", "ui", "runtime_id_mismatch", id="foreign-ui"),+ ],+)+def test_a_refused_desktop_start_leaves_everything_as_it_found_it(+ spawn, stop_env, caller, capsys, monkeypatch, found, part, reason+):+ # Refused before anything is announced: nothing is started or stopped, and+ # the status another Runtime published stays as it is.+ # With the lock held and no holder named, no service process is running either.+ foreign = spawn(OTHER_ID, {"service": "service", "lock-holder": None, "ui": "ui"}[found])+ _start_config(monkeypatch)+ monkeypatch.setattr(runtime, "start_service", lambda **kwargs: pytest.fail("no service may be started"))+ monkeypatch.setattr(runtime, "start_ui", lambda *args, **kwargs: pytest.fail("no UI may be started"))+ caller(RUNTIME_ID)+ status_path = paths.get_runtime_status_path()++ with contextlib.ExitStack() as held:+ if found == "ui":+ paths.get_runtime_ui_pid_path().write_text(str(foreign.pid), encoding="utf-8")+ runtime.write_status("running", "started", None, foreign.pid)+ else:+ held.enter_context(_service_lock_held_for(foreign if found == "service" else None))+ runtime.write_status("running", f"pid={foreign.pid}", foreign.pid, None)+ recorded = status_path.read_bytes()+ assert cli.cmd_start(open_browser=False) == 3++ assert _stderr_lines(capsys)[-1] == i18n_t("desktopRuntime.claimRefused", "en", part=part, reason=reason)+ assert stop_env["status"] == []+ assert status_path.read_bytes() == recorded+ assert stop_env["signals"] == []+ assert stop_env["stop_pid"] == []+ assert _alive(foreign)+++def test_a_ui_record_naming_another_program_does_not_refuse_a_desktop_start(spawn, stop_env, caller):+ # Quit leaves the UI record behind, and its pid may since name any program.+ program = spawn(OTHER_ID, None)+ paths.get_runtime_ui_pid_path().write_text(str(program.pid), encoding="utf-8")+ caller(RUNTIME_ID)++ runtime.claim_desktop_runtime_start()++ assert stop_env["signals"] == []+ assert _alive(program)+++def test_a_desktop_start_whose_service_lost_the_lock_to_another_runtime_rolls_back_only_its_own(+ spawn, stop_env, caller, capsys, monkeypatch+):+ # This start spawned its service and UI, but another Runtime's service took+ # the lock first. The start stops the two it spawned, and not the one that+ # took the lock.+ own_service = spawn(RUNTIME_ID)+ own_ui = spawn(RUNTIME_ID, "ui")+ foreign: list[subprocess.Popen] = []+ _start_config(monkeypatch)+ held = contextlib.ExitStack()++ def start_service(**kwargs):+ paths.get_runtime_pid_path().write_text(str(own_service.pid), encoding="utf-8")+ foreign.append(spawn(OTHER_ID))+ held.enter_context(_service_lock_held_for(foreign[0]))+ return kwargs["start_info"].capture(own_service.pid, reused=False)++ def start_ui(*args, start_info, **kwargs):+ paths.get_runtime_ui_pid_path().write_text(str(own_ui.pid), encoding="utf-8")+ return start_info.capture(own_ui.pid, reused=False)++ monkeypatch.setattr(runtime, "start_service", start_service)+ monkeypatch.setattr(runtime, "start_ui", start_ui)+ monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout: foreign[0].pid)+ caller(RUNTIME_ID)++ with held:+ assert cli.cmd_start(open_browser=False) == 3++ assert _stderr_lines(capsys)[-1] == i18n_t(+ "desktopRuntime.claimRefused", "en", part="service", reason="runtime_id_mismatch"+ )+ assert stop_env["stop_pid"] == [own_ui.pid, own_service.pid]+ assert not _signalled(stop_env, foreign[0])+ assert _alive(foreign[0])+++def test_a_failed_desktop_start_undoes_nothing_another_runtime_started_meanwhile(spawn, stop_env, caller, monkeypatch):+ # This start spawned its service and UI; before it finished, another+ # Runtime's UI replaced the UI record. Undoing the start stops the UI it+ # spawned and leaves the one on record.+ own_service = spawn(RUNTIME_ID)+ own_ui = spawn(RUNTIME_ID, "ui")+ foreign_ui = spawn(OTHER_ID, "ui")+ _start_config(monkeypatch)++ def start_service(**kwargs):+ paths.get_runtime_pid_path().write_text(str(own_service.pid), encoding="utf-8")+ return kwargs["start_info"].capture(own_service.pid, reused=False)++ def start_ui(*args, start_info, **kwargs):+ paths.get_runtime_ui_pid_path().write_text(str(own_ui.pid), encoding="utf-8")+ return start_info.capture(own_ui.pid, reused=False)++ def wait_for_service_ready(pid, timeout):+ paths.get_runtime_ui_pid_path().write_text(str(foreign_ui.pid), encoding="utf-8")+ raise RuntimeError("the readiness wait failed")++ monkeypatch.setattr(runtime, "start_service", start_service)+ monkeypatch.setattr(runtime, "start_ui", start_ui)+ monkeypatch.setattr(runtime, "wait_for_service_ready", wait_for_service_ready)+ caller(RUNTIME_ID)++ with pytest.raises(RuntimeError, match="the readiness wait failed"):+ cli.cmd_start(open_browser=False)++ assert stop_env["stop_pid"] == [own_ui.pid, own_service.pid]+ assert not _signalled(stop_env, foreign_ui)+ assert _alive(foreign_ui)++[email protected]("taken_over", ["service", "ui"])+def test_a_stop_asks_again_of_every_process_it_is_about_to_signal(+ spawn, stop_env, caller, capsys, monkeypatch, taken_over+):+ # Another Runtime replaced a part after the stop's first check passed.+ service = spawn(OTHER_ID if taken_over == "service" else RUNTIME_ID)+ ui = spawn(OTHER_ID if taken_over == "ui" else RUNTIME_ID, "ui")+ paths.get_runtime_ui_pid_path().write_text(str(ui.pid), encoding="utf-8")+ monkeypatch.setattr(runtime, "desktop_provenance_refusal", lambda **kwargs: None)+ caller(RUNTIME_ID)++ with _service_lock_held_for(service):+ assert cli.cmd_stop() == 3++ assert _stderr_lines(capsys)[-1] == i18n_t(+ "desktopRuntime.stopRefused", "en", part=taken_over, reason="runtime_id_mismatch"+ )+ foreign = service if taken_over == "service" else ui+ assert not _signalled(stop_env, foreign)+ assert _alive(foreign)+ # Nor is the tunnel connector the other Runtime's UI serves stopped.+ assert stop_env["remote_access"] == []+ assert stop_env["status"] == []+ assert stop_env["stop_pid"] == ([] if taken_over == "service" else [service.pid])+++def test_a_restart_job_stops_nothing_of_a_runtime_that_took_over_after_its_check(+ spawn, stop_env, caller, monkeypatch+):+ foreign = spawn(OTHER_ID)+ monkeypatch.setattr(runtime, "desktop_provenance_refusal", lambda **kwargs: None)+ caller(RUNTIME_ID)++ with _service_lock_held_for(foreign):+ rc = restart_supervisor._run_restart_job(job_id="jobtakenover", delay_seconds=0, vibe_path=None, trigger="test")++ assert rc == 3+ status = runtime.read_json(runtime.get_restart_status_path())+ assert (status["ok"], status["state"]) == (False, "failed")+ assert status["error"].startswith("restart refused: ")+ assert stop_env["stop_pid"] == []+ assert not _signalled(stop_env, foreign)+ assert _alive(foreign)++[email protected]("taken_over", ["service", "ui"])+def test_a_restart_job_s_successor_claims_only_its_own_runtime_and_undoes_what_it_started(+ spawn, stop_env, caller, monkeypatch, taken_over+):+ # Another Runtime came up while this job restarted: its UI is on record+ # when the successor starts, or its service takes the lock while the+ # successor is starting. The job neither adopts nor stops it, and stops+ # only what it started itself.+ caller(RUNTIME_ID)+ # The job runs from this Runtime's own tree, so its successor carries the id.+ monkeypatch.setenv(desktop_runtime.DESKTOP_RUNTIME_ROOT_ENV, str(Path(sys.executable).resolve().parent))+ started: dict[str, subprocess.Popen] = {}+ held = contextlib.ExitStack()++ def stop_runtime_for_restart(**kwargs):+ # The Runtime it replaces has stopped.+ if taken_over == "ui":+ started["foreign"] = spawn(OTHER_ID, "ui")+ paths.get_runtime_ui_pid_path().write_text(str(started["foreign"].pid), encoding="utf-8")+ return True, {}, 0.0, None, True, 0.0++ def start_service(**kwargs):+ if taken_over == "ui":+ pytest.fail("no service may be started")+ started["service"] = spawn(RUNTIME_ID)+ paths.get_runtime_pid_path().write_text(str(started["service"].pid), encoding="utf-8")+ started["foreign"] = spawn(OTHER_ID)+ held.enter_context(_service_lock_held_for(started["foreign"]))+ return kwargs["start_info"].capture(started["service"].pid, reused=False)++ def start_ui(*args, **kwargs):+ started["ui"] = spawn(RUNTIME_ID, "ui")+ paths.get_runtime_ui_pid_path().write_text(str(started["ui"].pid), encoding="utf-8")+ return kwargs["start_info"].capture(started["ui"].pid, reused=False)++ monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", stop_runtime_for_restart)+ monkeypatch.setattr(runtime, "start_service", start_service)+ monkeypatch.setattr(runtime, "start_ui", start_ui)+ monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout: started["foreign"].pid)+ runtime.write_status("stopped", "stopped", None, None)+ status_path = paths.get_runtime_status_path()+ recorded = status_path.read_bytes()++ with held:+ rc = restart_supervisor._run_restart_job(+ job_id=f"jobsuccessor{taken_over}", delay_seconds=0, vibe_path=None, trigger="test"+ )++ assert rc == 3+ status = runtime.read_json(runtime.get_restart_status_path())+ assert (status["ok"], status["state"]) == (False, "failed")+ assert status["error"].startswith("restart refused: ")+ if taken_over == "service":+ assert stop_env["stop_pid"] == [started["ui"].pid, started["service"].pid]+ else:+ # Refused before the successor announced anything.+ assert stop_env["stop_pid"] == []+ assert status_path.read_bytes() == recorded+ assert not _signalled(stop_env, started["foreign"])+ assert _alive(started["foreign"])+++def test_a_web_start_against_another_runtime_s_service_says_it_was_refused(spawn, stop_env, caller):+ foreign = spawn(OTHER_ID)+ caller(RUNTIME_ID)+ client = ui_server.app.test_client()++ with _service_lock_held_for(foreign):+ response = client.post("/api/control", json={"action": "start"}, headers=csrf_headers(client))++ assert response.status_code == 409+ payload = response.get_json()+ assert (payload["code"], payload["part"], payload["reason"]) == (+ "start_refused",+ "service",+ "runtime_id_mismatch",+ )+ assert stop_env["signals"] == []+ assert _alive(foreign)diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.pyindex 6f84ea516..006dc4e29 100644--- a/tests/test_remote_access_vibe_cloud.py+++ b/tests/test_remote_access_vibe_cloud.py@@ -2255,7 +2255,7 @@ def test_stop_ui_continues_when_remote_access_stop_fails(monkeypatch, tmp_path)timings = {}monkeypatch.setattr(remote_access, "stop", lambda: {"ok": False, "error": "cloudflared_stop_failed"})- monkeypatch.setattr(runtime, "stop_process", lambda pid_path: stop_calls.append(pid_path) or True)+ monkeypatch.setattr(runtime, "stop_process", lambda pid_path, **kwargs: stop_calls.append(pid_path) or True)assert runtime.stop_ui(timings) is Falseassert stop_calls == [paths.get_runtime_ui_pid_path()]@@ -2274,7 +2274,7 @@ def test_stop_ui_can_skip_remote_access_stop(monkeypatch, tmp_path) -> None:"stop",lambda: (_ for _ in ()).throw(AssertionError("remote access should stay running")),)- monkeypatch.setattr(runtime, "stop_process", lambda pid_path: stop_calls.append(pid_path) or True)+ monkeypatch.setattr(runtime, "stop_process", lambda pid_path, **kwargs: stop_calls.append(pid_path) or True)assert runtime.stop_ui(timings, stop_remote_access=False) is Trueassert stop_calls == [paths.get_runtime_ui_pid_path()]diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.pyindex 9300f077a..78ceb37a0 100644--- a/tests/test_restart_supervisor.py+++ b/tests/test_restart_supervisor.py@@ -331,8 +331,8 @@ def test_restart_job_stops_and_starts_service(monkeypatch, tmp_path, scope, readpaths.get_runtime_pid_path().write_text("111", encoding="utf-8")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, "_stop_runtime_for_restart", lambda stop_ui=True, **_kwargs: _fake_stop_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda start_ui=True, **_kwargs: _fake_start_runtime(calls))monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)@@ -448,11 +448,11 @@ def test_a_restart_relaunches_the_replaced_runtime_s_desktop_identity(calls = []relaunched = {}- def start(start_ui=True):+ def start(start_ui=True, **_kwargs):relaunched.update(os.environ)return _fake_start_runtime(calls)- monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda stop_ui=True: _fake_stop_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda stop_ui=True, **_kwargs: _fake_stop_runtime(calls))monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", start)monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid in alive)@@ -489,8 +489,8 @@ def test_restart_job_uses_lock_holder_when_pidfile_is_missing(monkeypatch, tmp_pcalls = []monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda: 111)- 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, "_stop_runtime_for_restart", lambda stop_ui=True, **_kwargs: _fake_stop_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda start_ui=True, **_kwargs: _fake_start_runtime(calls))monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)@@ -510,8 +510,8 @@ def test_restart_job_prepares_show_runtime_after_service_start(monkeypatch, tmp_paths.get_runtime_pid_path().write_text("111", encoding="utf-8")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, "_stop_runtime_for_restart", lambda stop_ui=True, **_kwargs: _fake_stop_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda start_ui=True, **_kwargs: _fake_start_runtime(calls))monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))monkeypatch.setattr(restart_supervisor, "get_restart_command", lambda vibe_path=None: ["/bin/vibe"])@@ -550,8 +550,8 @@ def test_restart_job_schedules_pending_followup_after_success(monkeypatch, tmp_pcalls = []scheduled: list[dict] = []- 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, "_stop_runtime_for_restart", lambda stop_ui=True, **_kwargs: _fake_stop_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda start_ui=True, **_kwargs: _fake_start_runtime(calls))monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)@@ -603,7 +603,7 @@ def test_restart_job_aborts_when_stop_fails(monkeypatch, tmp_path):monkeypatch.setattr(restart_supervisor,"_stop_runtime_for_restart",- lambda stop_ui=True: _fake_stop_runtime(calls, service_stopped=False),+ lambda stop_ui=True, **_kwargs: _fake_stop_runtime(calls, service_stopped=False),)monkeypatch.setattr(restart_supervisor, "_remaining_service_pids_after_stop", lambda: [111])monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)@@ -629,9 +629,9 @@ def test_restart_job_continues_when_old_pid_already_exited(monkeypatch, tmp_pathmonkeypatch.setattr(restart_supervisor,"_stop_runtime_for_restart",- lambda stop_ui=True: _fake_stop_runtime(calls, service_stopped=False),+ lambda stop_ui=True, **_kwargs: _fake_stop_runtime(calls, service_stopped=False),)- monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda start_ui=True: _fake_start_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda start_ui=True, **_kwargs: _fake_start_runtime(calls))monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)monkeypatch.setattr(restart_supervisor, "_remaining_service_pids_after_stop", lambda: [])monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)@@ -652,8 +652,8 @@ def test_restart_job_does_not_start_while_an_abandoned_installer_tree_survives(mpaths.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, "_stop_runtime_for_restart", lambda stop_ui=True, **_kwargs: _fake_stop_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda start_ui=True, **_kwargs: _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)@@ -674,10 +674,10 @@ def test_restart_job_aborts_when_extra_service_survives_stop(monkeypatch, tmp_pamonkeypatch.setattr(restart_supervisor,"_stop_runtime_for_restart",- lambda stop_ui=True: _fake_stop_runtime(calls, service_stopped=False),+ lambda stop_ui=True, **_kwargs: _fake_stop_runtime(calls, service_stopped=False),)monkeypatch.setattr(restart_supervisor, "_remaining_service_pids_after_stop", lambda: [333])- monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda start_ui=True: _fake_start_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda start_ui=True, **_kwargs: _fake_start_runtime(calls))monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)rc = restart_supervisor._run_restart_job(@@ -702,9 +702,9 @@ def test_restart_job_adopts_slow_starting_service_pid(monkeypatch, tmp_path):paths.get_runtime_pid_path().write_text("111", encoding="utf-8")calls = []- monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda stop_ui=True: _fake_stop_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda stop_ui=True, **_kwargs: _fake_stop_runtime(calls))monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)- def slow_start_runtime(start_ui=True):+ def slow_start_runtime(start_ui=True, **_kwargs):calls.append("start_runtime")runtime.write_status("starting", "service process is still starting", 222, 333)try:@@ -739,12 +739,12 @@ def test_restart_job_marks_start_runtime_failed(monkeypatch, tmp_path):paths.ensure_data_dirs()paths.get_runtime_pid_path().write_text("111", encoding="utf-8")- monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda stop_ui=True: _fake_stop_runtime([]))+ monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda stop_ui=True, **_kwargs: _fake_stop_runtime([]))monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)monkeypatch.setattr(restart_supervisor,"_start_runtime_processes",- lambda start_ui=True: (_ for _ in ()).throw(RuntimeError("service refused to start")),+ lambda start_ui=True, **_kwargs: (_ for _ in ()).throw(RuntimeError("service refused to start")),)rc = restart_supervisor._run_restart_job(job_id="jobtimeout", delay_seconds=0, vibe_path="/bin/vibe", trigger="test")@@ -763,8 +763,8 @@ def test_restart_job_waits_for_service_lock_release_before_start(monkeypatch, tmpaths.get_runtime_pid_path().write_text("111", encoding="utf-8")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, "_stop_runtime_for_restart", lambda stop_ui=True, **_kwargs: _fake_stop_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda start_ui=True, **_kwargs: _fake_start_runtime(calls))lock_checks = iter([(False, 111), (True, None)])@@ -791,12 +791,12 @@ def test_restart_job_fails_when_service_lock_does_not_release(monkeypatch, tmp_ppaths.get_runtime_pid_path().write_text("111", encoding="utf-8")calls = []- monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda stop_ui=True: _fake_stop_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda stop_ui=True, **_kwargs: _fake_stop_runtime(calls))monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: False)monkeypatch.setattr(restart_supervisor,"_start_runtime_processes",- lambda start_ui=True: (_ for _ in ()).throw(AssertionError("start should wait for lock release")),+ lambda start_ui=True, **_kwargs: (_ for _ in ()).throw(AssertionError("start should wait for lock release")),)monkeypatch.setattr(runtime, "pid_alive", lambda pid: False)@@ -873,7 +873,7 @@ def test_stop_runtime_for_restart_stops_ui_and_service(monkeypatch, tmp_path):ui_entered = threading.Event()service_entered = threading.Event()- def stop_ui(timings=None, *, stop_remote_access=True):+ def stop_ui(timings=None, *, stop_remote_access=True, **_kwargs):assert stop_remote_access is Falsecalls.append("stop_ui")ui_entered.set()@@ -884,7 +884,7 @@ def test_stop_runtime_for_restart_stops_ui_and_service(monkeypatch, tmp_path):monkeypatch.setattr(runtime, "stop_ui", stop_ui)- def stop_service():+ def stop_service(**_kwargs):calls.append("stop_service")service_entered.set()assert ui_entered.wait(timeout=1.0)@@ -939,11 +939,11 @@ def test_restart_job_service_scope_keeps_ui(monkeypatch, tmp_path):calls = []captured: dict[str, bool] = {}- def stub_stop(stop_ui=True):+ def stub_stop(stop_ui=True, **_kwargs):captured["stop_ui"] = stop_uireturn _fake_stop_runtime(calls)- def stub_start(start_ui=True):+ def stub_start(start_ui=True, **_kwargs):captured["start_ui"] = start_uireturn _fake_start_runtime(calls)@@ -973,9 +973,9 @@ def test_failed_upgrade_restart_reports_terminal_failure_without_package_rollbacpackage_commands = []calls = []- monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda stop_ui=True: _fake_stop_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda stop_ui=True, **_kwargs: _fake_stop_runtime(calls))monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)- monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda start_ui=True: _fake_start_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda start_ui=True, **_kwargs: _fake_start_runtime(calls))monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout: None)diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.pyindex f17ec32a6..f050f2402 100644--- a/tests/test_vibe_cli.py+++ b/tests/test_vibe_cli.py@@ -1082,9 +1082,9 @@ def test_cmd_stop_ignores_absent_services(monkeypatch):status = []monkeypatch.setattr(cli, "_pid_file_points_to_live_process", lambda path: False)- monkeypatch.setattr(runtime, "stop_service", lambda: False)- monkeypatch.setattr(runtime, "stop_ui", lambda: False)- monkeypatch.setattr(cli, "_stop_opencode_server", lambda: False)+ monkeypatch.setattr(runtime, "stop_service", lambda **kwargs: False)+ monkeypatch.setattr(runtime, "stop_ui", lambda **kwargs: False)+ monkeypatch.setattr(cli, "_stop_opencode_server", lambda *args: False)monkeypatch.setattr(cli, "_write_status", lambda state, detail=None: status.append((state, detail)))assert cli.cmd_stop() == 0@@ -1096,9 +1096,9 @@ def test_cmd_stop_fails_when_live_service_survives(monkeypatch, capsys):service_pid = paths.get_runtime_pid_path()monkeypatch.setattr(cli, "_pid_file_points_to_live_process", lambda path: path == service_pid)- monkeypatch.setattr(runtime, "stop_service", lambda: False)- monkeypatch.setattr(runtime, "stop_ui", lambda: False)- monkeypatch.setattr(cli, "_stop_opencode_server", lambda: False)+ monkeypatch.setattr(runtime, "stop_service", lambda **kwargs: False)+ monkeypatch.setattr(runtime, "stop_ui", lambda **kwargs: False)+ monkeypatch.setattr(cli, "_stop_opencode_server", lambda *args: False)monkeypatch.setattr(cli, "_write_status", lambda state, detail=None: status.append((state, detail)))assert cli.cmd_stop() == 2@@ -1111,9 +1111,9 @@ def test_cmd_stop_fails_when_lock_owner_survives_without_pidfile(monkeypatch, camonkeypatch.setattr(cli.runtime, "resolve_service_owner_pid", lambda include_starting=False: 1234)monkeypatch.setattr(cli.runtime, "ui_pid_file_points_to_running_ui", lambda: False)- monkeypatch.setattr(runtime, "stop_service", lambda: False)- monkeypatch.setattr(runtime, "stop_ui", lambda: False)- monkeypatch.setattr(cli, "_stop_opencode_server", lambda: False)+ monkeypatch.setattr(runtime, "stop_service", lambda **kwargs: False)+ monkeypatch.setattr(runtime, "stop_ui", lambda **kwargs: False)+ monkeypatch.setattr(cli, "_stop_opencode_server", lambda *args: False)monkeypatch.setattr(cli, "_write_status", lambda state, detail=None: status.append((state, detail)))assert cli.cmd_stop() == 2@@ -1310,7 +1310,7 @@ def start_runtime(monkeypatch):# someone else's live process: the real stop_ui() would signal pid 5678.# Record both calls instead of making them.monkeypatch.setattr(runtime, "stop_ui", lambda **kwargs: stopped.append("stop_ui") or True)- monkeypatch.setattr(runtime, "stop_service", lambda: stopped.append("stop_service") or True)+ monkeypatch.setattr(runtime, "stop_service", lambda **kwargs: stopped.append("stop_service") or True)return SimpleNamespace(service_path=service_path, ui_path=ui_path, spawned=spawned, opened=opened, stopped=stopped,)@@ -1417,7 +1417,7 @@ def test_cmd_start_ensures_services_without_stopping(monkeypatch):assert not any(call == "stop" for call in calls)-def _superseded_controller(monkeypatch, result, *, ui_running=False):+def _superseded_controller(monkeypatch, result):calls = []monkeypatch.setenv("AVIBE_DESKTOP_RUNTIME_ID", "b" * 64)monkeypatch.setattr(@@ -1430,7 +1430,6 @@ def _superseded_controller(monkeypatch, result, *, ui_running=False):"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@@ -1461,19 +1460,17 @@ def _left(role):@pytest.mark.parametrize(- ("result", "ui_running", "status"),+ ("result", "status"),[- (cli.runtime.DesktopRuntimeStopResult(refusal="service_runtime_id_mismatch"), False, 3),- (cli.runtime.DesktopRuntimeStopResult(remaining=_left("service")), False, 2),- (cli.runtime.DesktopRuntimeStopResult(remaining=_left("installer")), False, 2),- (cli.runtime.DesktopRuntimeStopResult(remaining=_left("opencode")), False, 2),- (cli.runtime.DesktopRuntimeStopResult(remaining=_left("unknown")), False, 2),- # Stopped, but a UI of some other Runtime still holds the pidfile.- (cli.runtime.DesktopRuntimeStopResult(), True, 3),+ (cli.runtime.DesktopRuntimeStopResult(refusal="service_runtime_id_mismatch"), 3),+ (cli.runtime.DesktopRuntimeStopResult(remaining=_left("service")), 2),+ (cli.runtime.DesktopRuntimeStopResult(remaining=_left("installer")), 2),+ (cli.runtime.DesktopRuntimeStopResult(remaining=_left("opencode")), 2),+ (cli.runtime.DesktopRuntimeStopResult(remaining=_left("unknown")), 2),],)-def test_desktop_start_fails_when_the_superseded_controller_is_not_stopped(monkeypatch, result, ui_running, status):- _superseded_controller(monkeypatch, result, ui_running=ui_running)+def test_desktop_start_fails_when_the_superseded_controller_is_not_stopped(monkeypatch, result, status):+ _superseded_controller(monkeypatch, result)# 3: this start does not take the home over; 2: part of it may still run.assert cli._handover_superseded_desktop_runtime(allowed=True) == status@@ -1765,7 +1762,7 @@ def _ui_refuses_to_start(raise ui_outcomereturn _fake_start_result(ui_outcome, kwargs, reused=ui_reused) if ui_outcome else None- def stop_service():+ def stop_service(**kwargs):calls.append("stop_service")return Truediff --git a/ui/src/components/settings/SettingsPlatformsPage.test.tsx b/ui/src/components/settings/SettingsPlatformsPage.test.tsxnew file mode 100644index 000000000..89672e914--- /dev/null+++ b/ui/src/components/settings/SettingsPlatformsPage.test.tsx@@ -0,0 +1,72 @@+/* @vitest-environment jsdom */++import { createInstance } from 'i18next';+import { cleanup, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';++const api = vi.hoisted(() => ({ getConfig: vi.fn(), mutateConfig: vi.fn() }));++vi.mock('../../context/ApiContext', () => ({ useApi: () => api }));+vi.mock('../../context/InstanceAuthorizationContext', () => ({+ useInstanceAuthorization: () => ({ capabilities: { can_manage_access_members: true } }),+}));+vi.mock('./SettingsPageShell', () => ({+ SettingsPageShell: ({ children }: { children: React.ReactNode }) => children,+}));+vi.mock('./PlatformConfigEmbed', () => ({ PlatformConfigEmbed: () => null }));++import { ToastProvider } from '../../context/ToastProvider';+import en from '../../i18n/en.json';+import { SettingsPlatformsPage } from './SettingsPlatformsPage';++const renderPage = () => {+ const i18n = createInstance();+ void i18n.use(initReactI18next).init({+ lng: 'en',+ resources: { en: { translation: en } },+ interpolation: { escapeValue: false },+ });+ return render(+ <I18nextProvider i18n={i18n}>+ <ToastProvider>+ <SettingsPlatformsPage />+ </ToastProvider>+ </I18nextProvider>,+ );+};++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe('config save whose restart the server refused', () => {+ it('says the change was saved but the service was not restarted', async () => {+ // WeChat is runnable once configured, so checking its tile enables it at once.+ const config = { platforms: { enabled: [] }, wechat: {} };+ api.getConfig.mockResolvedValue(config);+ // The /api/config answer when the hot reload failed and the fallback+ // restart was refused because the Avibe running here is not this desktop+ // Runtime's.+ api.mutateConfig.mockResolvedValue({+ ...config,+ platforms: { enabled: ['wechat'] },+ platform_runtime: {+ ok: false,+ hot_reconciled: false,+ restart_scheduled: false,+ restart_code: 'restart_refused',+ restart_error: "restart refused: the running service is not this desktop Runtime's (runtime_id_mismatch)",+ },+ });+ renderPage();++ await userEvent.click(await screen.findByRole('button', { name: /WeChat/ }));++ expect(api.mutateConfig).toHaveBeenCalledTimes(1);+ expect(await screen.findByText(en.settings.configRestartRefused)).toBeTruthy();+ expect(screen.queryByText(en.platform.restartedSuccess)).toBeNull();+ });+});diff --git a/ui/src/components/settings/SettingsPlatformsPage.tsx b/ui/src/components/settings/SettingsPlatformsPage.tsxindex 6ba89d39d..3a38006ac 100644--- a/ui/src/components/settings/SettingsPlatformsPage.tsx+++ b/ui/src/components/settings/SettingsPlatformsPage.tsx@@ -107,6 +107,10 @@ export const SettingsPlatformsPage: React.FC = () => {showToast(t('platform.restartedSuccess'), 'success');return true;}+ if (runtime?.restart_code === 'restart_refused') {+ showToast(t('settings.configRestartRefused'), 'error');+ return false;+ }if (runtime && runtime.hot_reconciled === false) {showToast(t('platform.restartFailed'), 'error');return false;diff --git a/ui/src/components/settings/SettingsServicePage.test.tsx b/ui/src/components/settings/SettingsServicePage.test.tsxnew file mode 100644index 000000000..cdca8b970--- /dev/null+++ b/ui/src/components/settings/SettingsServicePage.test.tsx@@ -0,0 +1,88 @@+/* @vitest-environment jsdom */++import { createInstance } from 'i18next';+import { cleanup, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { MemoryRouter } from 'react-router-dom';+import { afterEach, describe, expect, it, vi } from 'vitest';++const api = vi.hoisted(() => ({ getConfig: vi.fn(), mutateConfig: vi.fn() }));+const statusContext = vi.hoisted(() => ({+ status: { state: 'running', service_pid: 4321 },+ health: true,+ refreshStatus: vi.fn(),+ control: vi.fn(),+}));++vi.mock('../../context/ApiContext', () => ({ useApi: () => api }));+vi.mock('../../context/StatusContext', () => ({ useStatus: () => statusContext }));+vi.mock('./SettingsPageShell', () => ({+ SettingsPageShell: ({ children }: { children: React.ReactNode }) => children,+}));++import en from '../../i18n/en.json';+import { SettingsServicePage } from './SettingsServicePage';++const renderPage = () => {+ const i18n = createInstance();+ void i18n.use(initReactI18next).init({+ lng: 'en',+ resources: { en: { translation: en } },+ interpolation: { escapeValue: false },+ });+ return render(+ <I18nextProvider i18n={i18n}>+ <MemoryRouter>+ <SettingsServicePage />+ </MemoryRouter>+ </I18nextProvider>,+ );+};++afterEach(() => {+ cleanup();+ statusContext.status = { state: 'running', service_pid: 4321 };+ vi.clearAllMocks();+ vi.restoreAllMocks();+});++describe('service control refused by the server', () => {+ it('tells the person the restart did not happen and why', async () => {+ api.getConfig.mockResolvedValue({ ui: {} });+ // What StatusProvider.control throws for the 409 /api/control answers when+ // the Avibe running here is not this desktop Runtime's.+ statusContext.control.mockRejectedValue(+ Object.assign(new Error('Control action restart failed with status 409'), { code: 'restart_refused' }),+ );+ vi.spyOn(console, 'error').mockImplementation(() => {});+ renderPage();++ const restart = screen.getByRole('button', { name: en.common.restart });+ await userEvent.click(restart);++ expect(statusContext.control).toHaveBeenCalledWith('restart');+ expect(await screen.findByText(en.settings.restartRefused)).toBeTruthy();+ expect(screen.queryByText('PID 4321')).toBeNull();+ expect((restart as HTMLButtonElement).disabled).toBe(false);+ });++ it('tells the person the start did not happen and why', async () => {+ api.getConfig.mockResolvedValue({ ui: {} });+ statusContext.status = { state: 'stopped', service_pid: 4321 };+ // What StatusProvider.control throws for the 409 /api/control answers when+ // the service running here is not this desktop Runtime's.+ statusContext.control.mockRejectedValue(+ Object.assign(new Error('Control action start failed with status 409'), { code: 'start_refused' }),+ );+ vi.spyOn(console, 'error').mockImplementation(() => {});+ renderPage();++ const start = screen.getByRole('button', { name: en.common.start });+ await userEvent.click(start);++ expect(statusContext.control).toHaveBeenCalledWith('start');+ expect(await screen.findByText(en.settings.startRefused)).toBeTruthy();+ expect((start as HTMLButtonElement).disabled).toBe(false);+ });+});diff --git a/ui/src/components/settings/SettingsServicePage.tsx b/ui/src/components/settings/SettingsServicePage.tsxindex e8cca8aa0..96967877b 100644--- a/ui/src/components/settings/SettingsServicePage.tsx+++ b/ui/src/components/settings/SettingsServicePage.tsx@@ -34,6 +34,7 @@ export const SettingsServicePage: React.FC = () => {const [uiMessage, setUiMessage] = useState<string | null>(null);const [nameSaving, setNameSaving] = useState(false);const [nameMessage, setNameMessage] = useState<string | null>(null);+ const [controlMessage, setControlMessage] = useState<string | null>(null);useEffect(() => {api.getConfig().then(setConfig).catch(() => {});@@ -43,10 +44,19 @@ export const SettingsServicePage: React.FC = () => {const handleAction = async (action: string) => {setLoading(true);+ setControlMessage(null);try {await control(action);} catch (e) {console.error('Service control action failed', e);+ // The server stopped and started nothing: the Avibe running here is not+ // this desktop Runtime's, and the person needs to know the action did not happen.+ const code = (e as { code?: unknown } | null)?.code;+ if (code === 'restart_refused') {+ setControlMessage(t('settings.restartRefused'));+ } else if (code === 'start_refused') {+ setControlMessage(t('settings.startRefused'));+ }} finally {setLoading(false);}@@ -204,7 +214,7 @@ export const SettingsServicePage: React.FC = () => {><SettingsRowtitle={t('settings.statusNow')}- description={`PID ${status.service_pid || status.pid || '-'}`}+ description={controlMessage || `PID ${status.service_pid || status.pid || '-'}`}control={<div className="flex flex-wrap gap-2">{!isRunning && (diff --git a/ui/src/components/settings/shared/useBackendRuntime.ts b/ui/src/components/settings/shared/useBackendRuntime.tsindex 391c2c438..aeed5e3a3 100644--- a/ui/src/components/settings/shared/useBackendRuntime.ts+++ b/ui/src/components/settings/shared/useBackendRuntime.ts@@ -64,10 +64,15 @@ type BackendRuntimeApplyResult = {restart_scheduled?: boolean;apply_on_next_start?: boolean;restart_error?: string;+ restart_code?: string;error?: string;};-const assertBackendRuntimeApplied = (savedConfig: unknown, fallbackMessage: string) => {+const assertBackendRuntimeApplied = (+ savedConfig: unknown,+ fallbackMessage: string,+ refusedMessage: string,+) => {const runtime = (savedConfig as { agent_backend_runtime?: BackendRuntimeApplyResult } | null)?.agent_backend_runtime;@@ -79,6 +84,7 @@ const assertBackendRuntimeApplied = (savedConfig: unknown, fallbackMessage: stri) {return;}+ if (runtime.restart_code === 'restart_refused') throw new Error(refusedMessage);throw new Error(runtime.restart_error || runtime.error || fallbackMessage);};@@ -223,7 +229,7 @@ export function useBackendRuntime({const saved = await api.mutateConfig([setConfigField(['agents', backend, 'cli_path'], path)]);if (!mounted.current) return;setSavedCliPath(path); // persistence succeeded even if application failed- assertBackendRuntimeApplied(saved, t('common.saveFailed'));+ assertBackendRuntimeApplied(saved, t('common.saveFailed'), t('settings.configRestartRefused'));showToast(t('common.saved'), 'success');} catch (e) {if (mounted.current) showToast(errorMessage(e) || t('common.saveFailed'), 'error');@@ -250,7 +256,7 @@ export function useBackendRuntime({if (!mounted.current || enabledIntent.current !== intent) return;const persisted = savedConfig?.agents?.[backend]?.enabled;setEnabled(typeof persisted === 'boolean' ? persisted : next);- assertBackendRuntimeApplied(savedConfig, t('common.saveFailed'));+ assertBackendRuntimeApplied(savedConfig, t('common.saveFailed'), t('settings.configRestartRefused'));} catch (e) {if (!mounted.current || enabledIntent.current !== intent) return;showToast(errorMessage(e) || t('common.saveFailed'), 'error');diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsxindex e87cf7cde..fa5702e28 100644--- a/ui/src/components/steps/AgentDetection.tsx+++ b/ui/src/components/steps/AgentDetection.tsx@@ -472,7 +472,9 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onconst saved = await api.mutateConfig([setConfigField(['agents', backend, 'enabled'], enabled)]);const applied = saved?.agent_backend_runtime;if (applied && !applied.hot_reconciled && !applied.restart_scheduled && !applied.apply_on_next_start) {- receiptError = applied.restart_error || applied.error || t('onboarding.connection.applyFailed');+ receiptError = applied.restart_code === 'restart_refused'+ ? t('settings.configRestartRefused')+ : applied.restart_error || applied.error || t('onboarding.connection.applyFailed');}} catch (error) { receiptError = String(error); }if (enableIntent.current[backend] !== intent) return;diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 4fb2097be..4a2169e4c 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -495,6 +495,9 @@"serviceRuntimeTitle": "Runtime control","serviceRuntimeSubtitle": "Start, stop, and restart the local Avibe service while checking the live process state.","statusNow": "Current state",+ "restartRefused": "Not restarted: the Avibe running here could not be confirmed as this desktop app's own. Nothing was stopped.",+ "startRefused": "Not started: the Avibe running here could not be confirmed as this desktop app's own. It was left running.",+ "configRestartRefused": "Saved, but the service was not restarted: the Avibe running here could not be confirmed as this desktop app's own.","consoleServerTitle": "Console server","consoleServerHint": "Saving these values restarts only the Web UI server.","instanceNameTitle": "Instance name",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex c4b1a586e..6393ca5f2 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -495,6 +495,9 @@"serviceRuntimeTitle": "运行控制","serviceRuntimeSubtitle": "查看本地 Avibe 进程状态,并执行启动、停止和重启。","statusNow": "当前状态",+ "restartRefused": "未重启:无法确认此处运行的 Avibe 属于这个桌面应用,未停止任何进程。",+ "startRefused": "未启动:无法确认此处运行的 Avibe 属于这个桌面应用,它仍在运行。",+ "configRestartRefused": "已保存,但未重启服务:无法确认此处运行的 Avibe 属于这个桌面应用。","consoleServerTitle": "控制台服务","consoleServerHint": "保存这些值只会重启 Web UI 服务,不会重启主服务。","instanceNameTitle": "实例名称",diff --git a/vibe/cli.py b/vibe/cli.pyindex 1c9a2cca6..97c5cada7 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -13670,11 +13670,8 @@ def _handover_superseded_desktop_runtime(*, allowed: bool) -> int:if result.failure is not None:print(i18n_t("desktopRuntime.handoverFailed", language, part=result.failure), file=sys.stderr)return 2- # 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():- print(i18n_t("desktopRuntime.handoverForeignUi", language), file=sys.stderr)- return 3+ # Anything still running is not the superseded Runtime's; the start claims+ # only what carries this Runtime's id.return 0@@ -13685,6 +13682,14 @@ def cmd_start(*, open_browser: bool | None = None, hand_over: bool = False):handover_status = _handover_superseded_desktop_runtime(allowed=hand_over)if handover_status:return handover_status+ # Before anything is announced: a start refused here leaves the status, and+ # everything running, as it found them. The start below claims again what+ # it reuses and ends up with.+ try:+ runtime.claim_desktop_runtime_start()+ except runtime.DesktopRuntimeClaimRefused as refusal:+ _print_provenance_refusal("desktopRuntime.claimRefused", refusal)+ return 3has_configured_platform_credentials = getattr(config, "has_configured_platform_credentials", None)if callable(has_configured_platform_credentials):@@ -13764,6 +13769,7 @@ def cmd_start(*, open_browser: bool | None = None, hand_over: bool = False):)service_ready = resolved_pid is not Noneif resolved_pid is not None:+ runtime.claim_ready_service(resolved_pid, started_pid=service_pid)service_pid = resolved_pidif service_ready:runtime.write_status("running", "pid={}".format(service_pid), service_pid, ui_pid)@@ -13791,7 +13797,7 @@ def cmd_start(*, open_browser: bool | None = None, hand_over: bool = False):if not opened:print(f"(Tip) Could not auto-open a browser. Open this URL manually: {ui_url}")print("")- except BaseException:+ except BaseException as exc:# The invariant is that this invocation leaves running nothing it# created -- not just the service. The region starts two processes, and# a guard that undid one left the other exactly as orphaned: a UI this@@ -13806,28 +13812,31 @@ def cmd_start(*, open_browser: bool | None = None, hand_over: bool = False):# the undo runs in reverse order of creation -- the UI, then the service# it was pointed at.#- # Both undos find their process through its pid record rather than the- # captured pid, and that is sound by construction, not by luck: the- # spawn primitives write the record and then capture the child, both- # inside the region that kills the child if either step fails. So every- # live process this sees as created has a record naming it, and no- # child that missed the capture is still alive.- if ui_start.pid is not None and not ui_start.reused:- # `stop_remote_access=False`, the same distinction the stale-UI- # restart above makes, and for the same reason: `vibe start` never- # brings a tunnel up. `remote_access.start()` is reached only from- # the UI's explicit endpoint and from `vibe remote`; UI startup only- # starts monitors. Any tunnel alive here therefore predates this- # command, and tearing it down would destroy a remote URL this- # invocation did not create -- the one irreversible mistake- # available to a rollback.- runtime.stop_ui(stop_remote_access=False)- if service_start.pid is not None and not service_start.reused:- # A service that was already running is not ours to stop, and against- # one this command has then changed nothing to undo. stop_service()- # logs any pid it could not stop, so a rollback that itself fails- # still leaves evidence; either way the start has failed.- runtime.stop_service()+ # Without a desktop Runtime id, both undos find their process through+ # its pid record rather than the captured pid, and that is sound by+ # construction, not by luck: the spawn primitives write the record and+ # then capture the child, both inside the region that kills the child+ # if either step fails. So every live process this sees as created has+ # a record naming it, and no child that missed the capture is still+ # alive.+ #+ # The UI stop leaves the tunnel alone: `vibe start` never brings a+ # tunnel up. `remote_access.start()` is reached only from the UI's+ # explicit endpoint and from `vibe remote`; UI startup only starts+ # monitors. Any tunnel alive here therefore predates this command, and+ # tearing it down would destroy a remote URL this invocation did not+ # create -- the one irreversible mistake available to a rollback.+ #+ # A service that was already running is not ours to stop, and against+ # one this command has then changed nothing to undo. stop_service()+ # logs any pid it could not stop, so a rollback that itself fails still+ # leaves evidence; either way the start has failed. Under a desktop+ # Runtime id only the processes this start created are stopped, so one+ # another Runtime started meanwhile is left running.+ runtime.roll_back_start(service_start, ui_start)+ if isinstance(exc, runtime.DesktopRuntimeClaimRefused):+ _print_provenance_refusal("desktopRuntime.claimRefused", exc)+ return 3raiseif service_ready:from vibe.install_generations import collect_install_generations@@ -13871,8 +13880,11 @@ def cmd_vibe():return cmd_start()-def _stop_opencode_server():- """Terminate the OpenCode server if running."""+def _stop_opencode_server(runtime_ids: frozenset[str] = frozenset()):+ """Terminate the OpenCode server if running; with ``runtime_ids``, only that Runtime's.++ A server of another Runtime is left running, as the scoped stop leaves it.+ """pid_file = paths.get_logs_dir() / "opencode_server.json"if not pid_file.exists():return False@@ -13895,6 +13907,11 @@ def _stop_opencode_server():return Falseif "opencode" not in cmd or "serve" not in cmd:return False+ try:+ runtime.refuse_foreign_desktop_process(pid, "opencode", runtime_ids)+ except runtime.DesktopRuntimeClaimRefused as refusal:+ logger.warning("Leaving the OpenCode server pid=%s running: %s", pid, refusal)+ return Falseif runtime.stop_pid(pid, timeout=5):pid_file.unlink(missing_ok=True)@@ -14007,22 +14024,58 @@ def _stop_the_home_s_connector() -> int:return outcome[0]+def _print_provenance_refusal(key: str, refusal: runtime.DesktopRuntimeClaimRefused) -> None:+ print(+ i18n_t(key, _configured_cli_language(), part=refusal.part, reason=refusal.reason),+ file=sys.stderr,+ )+++def _desktop_provenance_refused(+ key: str,+ *,+ include_ui: bool = True,+ runtime_ids: frozenset[str] | None = None,+) -> bool:+ """Print why a desktop caller may not act on the Avibe running here, if it may not."""++ refusal = runtime.desktop_provenance_refusal(include_ui=include_ui, runtime_ids=runtime_ids)+ if refusal is None:+ return False+ _print_provenance_refusal(key, refusal)+ return True++def cmd_stop(*, expect_runtime_id: str | None = None):+ from vibe.desktop_runtime import desktop_caller_provenance+if expect_runtime_id is not None:return _stop_expected_desktop_runtime(expect_runtime_id)+ # The service and UI are asked first, so a refusal stops nothing, and+ # again by each stop of the processes it is about to signal, so a Runtime+ # that took over in between is refused too. An OpenCode server of another+ # Runtime is left running.+ provenance = desktop_caller_provenance()+ if _desktop_provenance_refused("desktopRuntime.stopRefused", runtime_ids=provenance):+ return 3service_was_running = _pid_file_points_to_live_process(paths.get_runtime_pid_path())ui_was_running = _pid_file_points_to_live_process(paths.get_runtime_ui_pid_path())- service_stopped = runtime.stop_service()- ui_stopped = runtime.stop_ui()+ try:+ service_stopped = runtime.stop_service(runtime_ids=provenance)+ ui_stopped = runtime.stop_ui(runtime_ids=provenance)+ except runtime.DesktopRuntimeClaimRefused as refusal:+ _print_provenance_refusal("desktopRuntime.stopRefused", refusal)+ return 3from 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()+ # whichever stop above failed. It reaps the trees of the Runtime this stop+ # acts for; a caller naming two Runtimes acts for neither.+ installers_reaped = len(provenance) > 1 or reap_abandoned_desktop_backend_installs(*provenance)# Also terminate OpenCode server on full stop- if _stop_opencode_server():+ if _stop_opencode_server(provenance):_report_opencode_stopped()if service_was_running and service_stopped is False:@@ -16589,6 +16642,9 @@ def _generation_downgrade_blocks(command: str | None, *, allow_downgrade: bool =def _cmd_restart_with_delay(delay_seconds: float) -> int:+ # Checked again by the restart job, which acts on whatever runs by then.+ if _desktop_provenance_refused("desktopRuntime.restartRefused"):+ return 3if delay_seconds > 0:return _schedule_delayed_restart(delay_seconds)diff --git a/vibe/desktop_runtime.py b/vibe/desktop_runtime.pyindex 507915a3d..7d0cdca67 100644--- a/vibe/desktop_runtime.py+++ b/vibe/desktop_runtime.py@@ -9,8 +9,10 @@ configuration or broaden its navigation policy.from __future__ import annotationsimport ipaddress+import jsonimport osimport socket+import sysfrom collections.abc import Mappingfrom pathlib import Pathfrom typing import Literal, TypedDict@@ -18,6 +20,17 @@ from typing import Literal, TypedDictDESKTOP_ENDPOINT_SCHEMA_VERSION: Literal[1] = 1DESKTOP_RUNTIME_ID_ENV = "AVIBE_DESKTOP_RUNTIME_ID"DESKTOP_RUNTIME_ROOT_ENV = "AVIBE_DESKTOP_RUNTIME_ROOT"+# The install marker the desktop host writes at the root of every private tree+# it unpacks: `INSTALL_MARKER_NAME` and `write_marker` in+# desktop/runtime-host/src/private_runtime.rs. Its `archive_sha256` is the id+# the launcher stamps as AVIBE_DESKTOP_RUNTIME_ID; its `python_entrypoint` is the+# tree-relative interpreter the launcher runs.+DESKTOP_RUNTIME_MARKER_NAME = ".avibe-runtime.json"+_DESKTOP_RUNTIME_MARKER_MAX_BYTES = 32 * 1024+# The directories between a tree root and its interpreter, one per+# `python_entrypoint` in desktop/runtime-sources.json: `python/bin/python3` and+# `python/python.exe`.+_DESKTOP_INTERPRETER_DIRS = (("python", "bin"), ("python",))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"@@ -43,14 +56,92 @@ class DesktopEndpointPayload(TypedDict):origin: str+def _runtime_id_value(value: object) -> str | None:+ if not isinstance(value, str) or len(value) != 64:+ return None+ if any(character not in "0123456789abcdef" for character in value):+ return None+ return value++def desktop_runtime_id(base_env: Mapping[str, str] | None = None) -> str | None:"""Return the validated identity of a desktop-managed Runtime."""env = os.environ if base_env is None else base_env- value = env.get(DESKTOP_RUNTIME_ID_ENV, "")- if len(value) != 64 or any(character not in "0123456789abcdef" for character in value):+ return _runtime_id_value(env.get(DESKTOP_RUNTIME_ID_ENV, ""))+++def _desktop_tree_runtime_id(executable: str | os.PathLike[str] | None) -> str | None:+ """The id of the private tree whose interpreter *executable* is, or None.++ Only the marker at the root of that tree counts: the directory the+ interpreter's own layout puts the root at, holding a valid+ `archive_sha256`, whose `python_entrypoint` leads back to this very+ interpreter. A marker anywhere else says nothing about who is running, and+ neither does one that fails any of these.+ """++ if not executable:return None- return value+ try:+ interpreter = Path(executable).resolve(strict=True)+ except (OSError, RuntimeError):+ return None+ parents = interpreter.parents+ for dirs in _DESKTOP_INTERPRETER_DIRS:+ if len(parents) <= len(dirs) or tuple(parent.name for parent in parents[: len(dirs)]) != dirs[::-1]:+ continue+ root = parents[len(dirs)]+ marker = root / DESKTOP_RUNTIME_MARKER_NAME+ if os.path.lexists(marker):+ return _desktop_marker_runtime_id(root, marker, interpreter)+ return None+++def _desktop_marker_runtime_id(root: Path, marker: Path, interpreter: Path) -> str | None:+ try:+ if marker.is_symlink() or not marker.is_file():+ return None+ with marker.open("rb") as handle:+ raw = handle.read(_DESKTOP_RUNTIME_MARKER_MAX_BYTES + 1)+ except OSError:+ return None+ if len(raw) > _DESKTOP_RUNTIME_MARKER_MAX_BYTES:+ return None+ try:+ manifest = json.loads(raw)+ except ValueError:+ return None+ if not isinstance(manifest, dict):+ return None+ runtime_id = _runtime_id_value(manifest.get("archive_sha256"))+ entrypoint = manifest.get("python_entrypoint")+ if runtime_id is None or not isinstance(entrypoint, str) or not entrypoint:+ return None+ if Path(entrypoint).is_absolute():+ return None+ try:+ if (root / entrypoint).resolve(strict=True) != interpreter:+ return None+ except (OSError, RuntimeError):+ return None+ return runtime_id+++def desktop_caller_provenance() -> frozenset[str]:+ """The desktop Runtime ids this process can act for.++ A process carries the id the launcher stamped into its environment, and+ runs from the tree its interpreter was unpacked into; either one makes it a+ desktop caller. An empty set is a caller with no desktop provenance at all:+ a terminal user managing their own Avibe.+ """++ ids = {+ desktop_runtime_id(),+ _desktop_tree_runtime_id(sys.executable),+ }+ return frozenset(value for value in ids if value is not None)def private_desktop_runtime_root(base_env: Mapping[str, str] | None = None) -> Path | None:diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex d93c8d07d..55809706b 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -846,7 +846,9 @@"handoverNotRequested": "Another desktop-managed Avibe Runtime is running here; this start does not replace it.","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."+ "claimRefused": "Another Avibe Runtime is running here and does not belong to this desktop app; nothing was stopped ({part}: {reason}).",+ "stopRefused": "Nothing was stopped: this command runs from a desktop-managed Avibe Runtime, and the running {part} is not that Runtime's ({reason}). Stop it from the Avibe that started it.",+ "restartRefused": "Nothing was restarted: this command runs from a desktop-managed Avibe Runtime, and the running {part} is not that Runtime's ({reason}). Restart it from the Avibe that started it."},"agentInstall": {"installFailed": "Could not install {backend}.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 80500d653..e7539fd9c 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -846,7 +846,9 @@"handoverNotRequested": "此处正在运行另一个桌面托管的 Avibe Runtime;本次启动不会替换它。","handoverRefused": "已拒绝停止被取代的桌面托管 Avibe Runtime:{reason}","handoverFailed": "未能停止被取代的桌面托管 Avibe Runtime:{part}",- "handoverForeignUi": "仍有一个不属于被取代的桌面托管 Avibe Runtime 的 UI 服务在运行。"+ "claimRefused": "此处正在运行另一个不属于本桌面应用的 Avibe Runtime;未停止任何进程({part}:{reason})。",+ "stopRefused": "未停止任何进程:此命令来自桌面托管的 Avibe Runtime,而正在运行的 {part} 不属于该 Runtime({reason})。请从启动它的 Avibe 停止它。",+ "restartRefused": "未重启任何进程:此命令来自桌面托管的 Avibe Runtime,而正在运行的 {part} 不属于该 Runtime({reason})。请从启动它的 Avibe 重启它。"},"agentInstall": {"installFailed": "无法安装 {backend}。",diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.pyindex 835f783cc..92f9fe96b 100644--- a/vibe/restart_supervisor.py+++ b/vibe/restart_supervisor.py@@ -24,6 +24,7 @@ from vibe.desktop_runtime import (DESKTOP_RUNTIME_ID_ENV,DESKTOP_RUNTIME_ROOT_ENV,DESKTOP_SHELL_ENV,+ desktop_caller_provenance,desktop_runtime_id,is_private_desktop_runtime_path,)@@ -269,11 +270,21 @@ def _runtime_ready_for_config(config) -> bool:def _start_runtime_processes(start_ui: bool = True,+ *,+ service_start: runtime.ProcessStartInfo | None = None,+ ui_start: runtime.ProcessStartInfo | None = None,) -> StartedRuntime:- """Start the service, and the UI when this job owns it."""+ """Start the service, and the UI when this job owns it.++ ``service_start`` and ``ui_start`` record what the start created, for a+ caller that has to undo it.+ """from core.services import settings as settings_service+ # Before the first status write, as `vibe start` claims: a successor that+ # would reuse another Runtime's process is refused with nothing announced.+ runtime.claim_desktop_runtime_start(include_ui=start_ui)paths.ensure_data_dirs()config = settings_service.load_config(default_factory=settings_service.default_config)# Service-only restart: the UI process was never stopped, so carry its@@ -290,6 +301,7 @@ def _start_runtime_processes(service_pid = runtime.start_service(wait_for_ready=False,initial_ready_timeout=0,+ start_info=service_start,)if start_ui:bind_host = runtime.effective_ui_bind_host(config)@@ -297,6 +309,7 @@ def _start_runtime_processes(bind_host,config.ui.setup_port,wait_for_ready=False,+ start_info=ui_start,)else:ui_pid = preserved_ui_pid@@ -315,29 +328,32 @@ def _start_runtime_processes(return StartedRuntime(service_pid, ui_pid)-def _stop_ui_for_restart() -> tuple[bool, dict[str, float | bool], float, int | None]:+def _stop_ui_for_restart(runtime_ids: frozenset[str]) -> tuple[bool, dict[str, float | bool], float, int | None]:timings: dict[str, float | bool] = {}started_at = time.monotonic()- stopped = runtime.stop_ui(timings, stop_remote_access=False)+ stopped = runtime.stop_ui(timings, stop_remote_access=False, runtime_ids=runtime_ids)return bool(stopped), timings, _rounded_seconds(time.monotonic() - started_at), _read_recorded_ui_pid()-def _stop_service_for_restart() -> tuple[bool, float]:+def _stop_service_for_restart(runtime_ids: frozenset[str]) -> tuple[bool, float]:started_at = time.monotonic()- stopped = runtime.stop_service()+ stopped = runtime.stop_service(runtime_ids=runtime_ids)return bool(stopped), _rounded_seconds(time.monotonic() - started_at)-def _stop_runtime_for_restart(stop_ui: bool = True) -> tuple[bool, dict[str, float | bool], float, int | None, bool, float]:+def _stop_runtime_for_restart(+ stop_ui: bool = True,+ runtime_ids: frozenset[str] = frozenset(),+) -> tuple[bool, dict[str, float | bool], float, int | None, bool, float]:if not stop_ui:# Service-only restart: leave the UI process untouched so the open Web# UI survives. Report its still-recorded pid; ``ui_stopped`` is True only# to satisfy the "did the UI stop" guard (we deliberately did not stop it).- service_stopped, stop_service_seconds = _stop_service_for_restart()+ service_stopped, stop_service_seconds = _stop_service_for_restart(runtime_ids)return True, {}, 0.0, _read_recorded_ui_pid(), service_stopped, stop_service_secondswith ThreadPoolExecutor(max_workers=2, thread_name_prefix="avibe-restart-stop") as executor:- ui_future = executor.submit(_stop_ui_for_restart)- service_future = executor.submit(_stop_service_for_restart)+ ui_future = executor.submit(_stop_ui_for_restart, runtime_ids)+ service_future = executor.submit(_stop_service_for_restart, runtime_ids)ui_stopped, ui_timings, stop_ui_seconds, ui_pid = ui_future.result()service_stopped, stop_service_seconds = service_future.result()return ui_stopped, ui_timings, stop_ui_seconds, ui_pid, service_stopped, stop_service_seconds@@ -431,11 +447,24 @@ def _run_restart_job(write("restart job started after delay")restart_started_at = time.monotonic()+ # Whoever asked, a desktop caller restarts only its own Runtime. Nothing+ # has been stopped yet, and nothing is. The ids it acts for are read+ # before the carry below rewrites its environment, and each stop asks+ # them again of the processes it is about to signal.+ provenance = desktop_caller_provenance()+ refusal = runtime.desktop_provenance_refusal(include_ui=restart_ui, runtime_ids=provenance)+ if refusal is not None:+ return fail(f"restart refused: {refusal}", 3, started_at=restart_started_at)write(f"relaunching {_carry_desktop_identity()}")write("stopping UI and service" if restart_ui else "stopping service (Web UI kept running)")stop_runtime_started_at = time.monotonic()try:- ui_stopped, ui_timings, stop_ui_seconds, ui_pid, stopped, stop_service_seconds = _stop_runtime_for_restart(stop_ui=restart_ui)+ ui_stopped, ui_timings, stop_ui_seconds, ui_pid, stopped, stop_service_seconds = _stop_runtime_for_restart(+ stop_ui=restart_ui,+ runtime_ids=provenance,+ )+ except runtime.DesktopRuntimeClaimRefused as exc:+ return fail(f"restart refused: {exc}", 3, started_at=restart_started_at)except Exception as exc:return fail(f"stop runtime failed: {exc}", 2, started_at=restart_started_at)stage_durations.update(ui_timings)@@ -449,8 +478,9 @@ def _run_restart_job(# 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():+ # start while it is. The trees reaped are those of the Runtime the+ # job acts for; a caller naming two Runtimes acts for neither.+ if len(provenance) < 2 and not reap_abandoned_desktop_backend_installs(*provenance):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()@@ -471,9 +501,21 @@ def _run_restart_job(write("starting service")start_runtime_started_at = time.monotonic()+ service_start = runtime.ProcessStartInfo()+ ui_start = runtime.ProcessStartInfo()++ def refuse_start(exc: runtime.DesktopRuntimeClaimRefused) -> int:+ # The successor claims exactly as `vibe start` does: a process of+ # another Runtime is neither adopted nor recorded as this one, and+ # only what this start created is stopped.+ runtime.roll_back_start(service_start, ui_start)+ return fail(f"restart refused: {exc}", 3, started_at=restart_started_at)+try:- started = _start_runtime_processes(start_ui=restart_ui)+ started = _start_runtime_processes(start_ui=restart_ui, service_start=service_start, ui_start=ui_start)new_pid, ui_pid = started.service_pid, started.ui_pid+ except runtime.DesktopRuntimeClaimRefused as exc:+ return refuse_start(exc)except Exception as exc:return fail(f"start runtime failed: {exc}", 1, started_at=restart_started_at)mark_duration("start_runtime_seconds", start_runtime_started_at)@@ -504,6 +546,11 @@ def _run_restart_job(3,started_at=restart_started_at,)+ try:+ runtime.claim_ready_service(resolved_pid, started_pid=new_pid)+ except runtime.DesktopRuntimeClaimRefused as exc:+ mark_duration("wait_service_lock_seconds", wait_lock_started_at)+ return refuse_start(exc)new_pid = resolved_pidmark_duration("wait_service_lock_seconds", wait_lock_started_at)recorded_ui_pid = service_status.get("ui_pid") if service_status else ui_piddiff --git a/vibe/runtime.py b/vibe/runtime.pyindex b401bd185..c97e76cfc 100644--- a/vibe/runtime.py+++ b/vibe/runtime.py@@ -1475,7 +1475,7 @@ def wait_for_service_pid(pid: int, timeout: float = SERVICE_LOCK_READY_TIMEOUT_Sreturn ready-def stop_process(pid_path, timeout=5):+def stop_process(pid_path, timeout=5, *, runtime_ids: frozenset[str] = frozenset(), part: str = "process"):if not pid_path.exists():return Falsetry:@@ -1486,6 +1486,7 @@ def stop_process(pid_path, timeout=5):if not pid_alive(pid):pid_path.unlink(missing_ok=True)return False+ refuse_foreign_desktop_process(pid, part, runtime_ids)stopped = stop_pid(pid, timeout=timeout)if stopped:pid_path.unlink(missing_ok=True)@@ -2068,6 +2069,7 @@ def start_service(ready_pid = wait_for_service_ready(pid, timeout=max(0.0, deadline - time.monotonic()))if ready_pid is None:_raise_service_started_but_never_ran(pid, timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS)+ claim_ready_service(ready_pid, started_pid=pid)if start_info is not None:start_info.capture(ready_pid, reused=start_info.reused)from vibe.install_generations import collect_install_generations@@ -2091,10 +2093,26 @@ def _resolve_service_pid("""from storage.migrations import guard_source_checkout_default_state_bootstrap+ from vibe.desktop_runtime import desktop_runtime_iddef result(pid: int, *, reused: bool) -> int:+ # A process this call did not start is reused only when it is the+ # caller's own desktop Runtime's; see claim_desktop_runtime_process.+ if reused:+ claim_desktop_runtime_process(pid, "service")return start_info.capture(pid, reused=reused) if start_info is not None else pid+ def already_running(*holder_pids: int | None) -> ServiceAlreadyRunningError:+ # A desktop start that finds a service it may not reuse says whose it+ # is not, as a reuse does; one nothing can name is nobody's to claim.+ if desktop_runtime_id() is not None:+ live = [pid for pid in holder_pids if pid and pid_alive(pid)]+ if not live:+ raise DesktopRuntimeClaimRefused("service", "identity_unavailable")+ for pid in live:+ claim_desktop_runtime_process(pid, "service")+ return ServiceAlreadyRunningError(lock_path=get_service_lock_path(), holder_pid=holder_pids[0])+guard_source_checkout_default_state_bootstrap()with _SERVICE_LOCK:pid_path = paths.get_runtime_pid_path()@@ -2129,8 +2147,7 @@ def _resolve_service_pid(existing_pid,)return result(lock_holder_pid, reused=True)- raise ServiceAlreadyRunningError(lock_path=get_service_lock_path(), holder_pid=lock_holder_pid)- raise ServiceAlreadyRunningError(lock_path=get_service_lock_path(), holder_pid=lock_holder_pid)+ raise already_running(lock_holder_pid)logger.warning("Ignoring stale service pid file pid=%s because it does not match the Vibe service",existing_pid,@@ -2141,11 +2158,11 @@ def _resolve_service_pid(if not lock_available:if lock_holder_pid and lock_holder_pid == existing_pid and pid_alive(lock_holder_pid):return result(lock_holder_pid, reused=True)- raise ServiceAlreadyRunningError(lock_path=get_service_lock_path(), holder_pid=lock_holder_pid)+ raise already_running(lock_holder_pid)extra_pids = extra_service_process_pids()if extra_pids:- raise ServiceAlreadyRunningError(lock_path=get_service_lock_path(), holder_pid=extra_pids[0])+ raise already_running(*extra_pids)launcher = launcher or current_service_launcher()scope_prefix = maybe_systemd_scope_prefix()@@ -2184,6 +2201,7 @@ def _resolve_service_pid(initial_ready_timeout=initial_ready_timeout,wait_for_ready=wait_for_ready,)+ claim_ready_service(resolved_pid, started_pid=pid)return result(resolved_pid, reused=False)if initial_ready_timeout > 0 and wait_for_service_pid(pid, timeout=initial_ready_timeout):return pid@@ -2427,11 +2445,12 @@ def start_ui(except Exception:existing_pid = 0if existing_pid and pid_alive(existing_pid):- if _pid_matches_ui_server(existing_pid) and _ui_server_compatible(host, port):+ is_ui_server = _claim_recorded_ui(existing_pid)+ if is_ui_server and _ui_server_compatible(host, port):if start_info is not None:start_info.capture(existing_pid, reused=True)return existing_pid- if _pid_matches_ui_server(existing_pid):+ if is_ui_server:logger.warning("Stopping stale UI process pid=%s because required listener or identity checks failed for %s",existing_pid,@@ -2482,7 +2501,14 @@ def start_ui(return pid-def stop_service():+def stop_service(*, runtime_ids: frozenset[str] = frozenset()):+ """Stop every service process; with ``runtime_ids``, only when all are that Runtime's.++ The ids are checked on the very processes this stop selected, before any+ of them is signalled, so a Runtime that took over since an earlier check+ is refused, not stopped.+ """+with _SERVICE_LOCK:pid_path = paths.get_runtime_pid_path()owner_pid = resolve_service_owner_pid()@@ -2496,6 +2522,8 @@ def stop_service():if recorded_pid and not pid_alive(recorded_pid):pid_path.unlink(missing_ok=True)return False+ for pid in target_pids:+ refuse_foreign_desktop_process(pid, "service", runtime_ids)stopped_all = Truefor pid in target_pids:@@ -2531,9 +2559,26 @@ def stop_remote_access_connector() -> bool:return True-def stop_ui(timings: dict[str, float | bool] | None = None, *, stop_remote_access: bool = True):+def stop_ui(+ timings: dict[str, float | bool] | None = None,+ *,+ stop_remote_access: bool = True,+ runtime_ids: frozenset[str] = frozenset(),+):+ """Stop the recorded UI and, by default, the tunnel connector it serves.++ With ``runtime_ids``, a UI that is not that Runtime's is refused, and so is+ its connector: the UI is checked before the connector stops, and again as+ the pid about to be signalled is read.+ """+remote_access_stopped = Truestarted_at = time.monotonic()+ ui_pid_path = paths.get_runtime_ui_pid_path()+ if stop_remote_access and runtime_ids:+ recorded_pid = _read_pid_file(ui_pid_path)+ if recorded_pid and pid_alive(recorded_pid):+ refuse_foreign_desktop_process(recorded_pid, "ui", runtime_ids)if stop_remote_access:remote_access_started_at = time.monotonic()remote_access_stopped = stop_remote_access_connector()@@ -2543,7 +2588,7 @@ def stop_ui(timings: dict[str, float | bool] | None = None, *, stop_remote_accestimings["stop_remote_access_seconds"] = 0.0timings["stop_remote_access_skipped"] = Trueui_started_at = time.monotonic()- ui_stopped = stop_process(paths.get_runtime_ui_pid_path())+ ui_stopped = stop_process(ui_pid_path, runtime_ids=runtime_ids, part="ui")if timings is not None:timings["stop_ui_process_seconds"] = _rounded_seconds(time.monotonic() - ui_started_at)timings["stop_ui_seconds"] = _rounded_seconds(time.monotonic() - started_at)@@ -2747,6 +2792,201 @@ def is_desktop_ui(pid: int, runtime_id: str | None) -> bool | None:return None+class DesktopRuntimeClaimRefused(RuntimeError):+ """A start or stop found a running ``part`` that is not its own Runtime's.++ ``reason`` is ``runtime_id_mismatch`` for a process carrying another id or+ none, and ``identity_unavailable`` when nothing can tell whose it is. The+ process is left as it is.+ """++ def __init__(self, part: str, reason: str) -> None:+ super().__init__(f"the running {part} is not this desktop Runtime's ({reason})")+ self.part = part+ self.reason = reason+++def _desktop_runtime_mismatch(pid: int, runtime_ids: frozenset[str]) -> str | None:+ """Why ``pid`` is not a process of the one Runtime ``runtime_ids`` names, or None.++ A caller that can act for two Runtimes acts for neither. A process that has+ exited is nobody's.+ """++ from vibe.desktop_runtime import desktop_runtime_id++ try:+ carried = desktop_runtime_id(psutil.Process(pid).environ())+ except psutil.NoSuchProcess:+ return None+ except (psutil.Error, OSError):+ return "identity_unavailable"+ if carried is None or runtime_ids != {carried}:+ return "runtime_id_mismatch"+ return None+++def claim_desktop_runtime_process(pid: int, part: str) -> None:+ """Raise ``DesktopRuntimeClaimRefused`` unless ``pid`` is this desktop Runtime's own.++ A start carrying a desktop Runtime id reuses, adopts or replaces only+ processes carrying the same id. A start without one claims as it always has.+ """++ from vibe.desktop_runtime import desktop_runtime_id++ runtime_id = desktop_runtime_id()+ if runtime_id is not None:+ refuse_foreign_desktop_process(pid, part, frozenset({runtime_id}))+++def refuse_foreign_desktop_process(pid: int, part: str, runtime_ids: frozenset[str]) -> None:+ """Raise ``DesktopRuntimeClaimRefused`` unless a caller acting for ``runtime_ids`` may act on ``pid``.++ No ids is a caller with no desktop provenance, which acts on anything.+ """++ if not runtime_ids:+ return+ reason = _desktop_runtime_mismatch(pid, runtime_ids)+ if reason is not None:+ raise DesktopRuntimeClaimRefused(part, reason)+++def claim_ready_service(ready_pid: int, *, started_pid: int) -> None:+ """Claim the lock holder a start ended up with when it is not the process it asked about.++ A service of another Runtime can take the lock first. The start's own+ record still names the process it created, which is what a rollback stops.+ """++ if ready_pid != started_pid:+ claim_desktop_runtime_process(ready_pid, "service")+++def _claim_recorded_ui(pid: int) -> bool:+ """Whether the live ``pid`` the UI record names is a UI server a start may reuse or replace.++ A record naming another program is stale. Under a desktop Runtime id a UI+ server must be that Runtime's, and a pid whose command line cannot be read+ is refused: nothing can tell whose it is.+ """++ from vibe.desktop_runtime import desktop_runtime_id++ is_ui_server = _pid_matches_ui_server(pid)+ if not is_ui_server and desktop_runtime_id() is not None and not get_process_command(pid):+ raise DesktopRuntimeClaimRefused("ui", "identity_unavailable")+ if is_ui_server:+ claim_desktop_runtime_process(pid, "ui")+ return is_ui_server+++def claim_desktop_runtime_start(*, include_ui: bool = True) -> None:+ """Raise ``DesktopRuntimeClaimRefused`` unless what a desktop start would reuse or replace is its Runtime's.++ Asked before the start announces anything, so a refused start leaves the+ status as it found it. The service is judged as a stop judges it, and with+ ``include_ui`` the recorded UI as ``start_ui`` judges it. A start without a+ desktop Runtime id claims as it always has.+ """++ from vibe.desktop_runtime import desktop_runtime_id++ runtime_id = desktop_runtime_id()+ if runtime_id is None:+ return+ refusal = desktop_provenance_refusal(include_ui=False, runtime_ids=frozenset({runtime_id}))+ if refusal is not None:+ raise refusal+ ui_pid = _read_pid_file(paths.get_runtime_ui_pid_path())+ if include_ui and ui_pid and pid_alive(ui_pid):+ _claim_recorded_ui(ui_pid)+++def _stop_created_process(pid: int, runtime_ids: frozenset[str]) -> bool:+ """Stop ``pid``, created by a start that did not finish, while it is that Runtime's; True once it is gone."""++ if not pid_alive(pid):+ return True+ reason = _desktop_runtime_mismatch(pid, runtime_ids)+ if reason is not None:+ logger.warning("A failed start leaves pid=%s running (%s)", pid, reason)+ return False+ if stop_pid(pid):+ return True+ logger.error("Failed to stop pid=%s, created by a failed start", pid)+ return False+++def roll_back_start(service_start: ProcessStartInfo, ui_start: ProcessStartInfo) -> None:+ """Stop what a start that did not finish created, the UI and then its service.++ Created is what the start infos record as not reused. The UI stop leaves the+ tunnel connector alone: a start never brings one up, so any connector alive+ predates it. Under a desktop Runtime id the rollback stops exactly the+ processes the start created, and only while they carry that id: what the+ records name by then may be another Runtime's.+ """++ from vibe.desktop_runtime import desktop_runtime_id++ runtime_id = desktop_runtime_id()+ ui_created = ui_start.pid is not None and not ui_start.reused+ service_created = service_start.pid is not None and not service_start.reused+ if runtime_id is None:+ if ui_created:+ stop_ui(stop_remote_access=False)+ if service_created:+ stop_service()+ return+ runtime_ids = frozenset({runtime_id})+ if ui_created and _stop_created_process(ui_start.pid, runtime_ids):+ _forget_pid_record(paths.get_runtime_ui_pid_path(), ui_start.pid)+ if service_created:+ with _SERVICE_LOCK:+ if _stop_created_process(service_start.pid, runtime_ids):+ _clear_service_pid_reservation(service_start.pid)+++def desktop_provenance_refusal(+ *,+ include_ui: bool = True,+ runtime_ids: frozenset[str] | None = None,+) -> DesktopRuntimeClaimRefused | None:+ """Why this caller may not stop or restart the Avibe running here, or None when it may.++ A caller with no desktop provenance manages whatever runs here, as it always+ has. A desktop caller acts only for its own Runtime: every service process,+ and with ``include_ui`` the recorded UI, must carry exactly its id, and a+ service lock held, or not probed, with no process named as its holder is+ refused. With nothing running there is nothing to refuse. ``runtime_ids``+ defaults to this caller's ``desktop_caller_provenance()``.+ """++ from vibe.desktop_runtime import desktop_caller_provenance++ provenance = desktop_caller_provenance() if runtime_ids is None else runtime_ids+ if not provenance:+ return None+ owner_pid = resolve_service_owner_pid()+ if owner_pid is None and desktop_service_lock_presence() is not DesktopRuntimePresence.ABSENT:+ return DesktopRuntimeClaimRefused("service", "identity_unavailable")+ service_pids = set(extra_service_process_pids(owner_pid=owner_pid))+ if owner_pid is not None:+ service_pids.add(owner_pid)+ parts = [("service", pid) for pid in sorted(service_pids)]+ if include_ui:+ ui_pid = _read_pid_file(paths.get_runtime_ui_pid_path())+ if ui_pid and pid_alive(ui_pid):+ parts.append(("ui", ui_pid))+ for part, pid in parts:+ reason = _desktop_runtime_mismatch(pid, provenance)+ if reason is not None:+ return DesktopRuntimeClaimRefused(part, reason)+ 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."""diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex a477a6d83..7a4ca289a 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -81,6 +81,7 @@ from storage.delivery_states import ADMITTED_DELIVERY_STATESif TYPE_CHECKING:from core.show_runtime import ShowRuntimeUnavailableError+ from vibe.runtime import DesktopRuntimeClaimRefusedlogger = logging.getLogger(__name__)@@ -6750,10 +6751,26 @@ def _restart_in_flight() -> bool:return age < _RESTART_SEED_GRACE_SECONDS+def _runtime_refusal_payload(action: str, refusal: "DesktopRuntimeClaimRefused") -> dict[str, Any]:+ return {+ "ok": False,+ "error": f"{action} refused: {refusal}",+ "code": f"{action}_refused",+ "part": refusal.part,+ "reason": refusal.reason,+ }++def _schedule_service_restart_for_config_fallback() -> dict[str, Any]:from vibe import runtimefrom vibe.restart_supervisor import mark_pending_restart, schedule_restart+ # The restart job refuses too; asking first keeps the runtime from being+ # marked restarting for a restart that will not happen.+ refusal = runtime.desktop_provenance_refusal(include_ui=False)+ if refusal is not None:+ return _runtime_refusal_payload("restart", refusal)+def _schedule_restart() -> dict[str, Any]:status = runtime.read_status()runtime.write_status("restarting", "restarting", status.get("service_pid"), status.get("ui_pid"))@@ -6857,7 +6874,15 @@ def control():status["last_action"] = actionif action == "start":runtime.ensure_config()- service_pid = runtime.start_service()+ try:+ service_pid = runtime.start_service()+ except runtime.DesktopRuntimeClaimRefused as refusal:+ # The service running here is another Runtime's: it is left+ # running, and the person is told why nothing started.+ return (+ jsonify({**_runtime_refusal_payload("start", refusal), "action": action, "status": runtime.read_status()}),+ 409,+ )runtime.write_status("running", "started", service_pid, status.get("ui_pid"))elif action == "stop":runtime.write_status("stopping", "stopping", status.get("service_pid"), status.get("ui_pid"))@@ -6892,6 +6917,12 @@ def control():),409,)+ refusal = runtime.desktop_provenance_refusal(include_ui=scope != "service")+ if refusal is not None:+ return (+ jsonify({**_runtime_refusal_payload("restart", refusal), "action": action, "status": runtime.read_status()}),+ 409,+ )runtime.write_status("restarting", "restarting", status.get("service_pid"), status.get("ui_pid"))result = schedule_restart(delay_seconds=0.0, trigger="web-ui", scope=scope)return jsonify({"ok": True, "action": action, "restart": result, "status": runtime.read_status()})