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): scoped stop takes the tunnel down, restart keeps the desktop identity, removal claims installs (#2267)
Call White90f178026e79
diff --git a/tests/test_desktop_backends.py b/tests/test_desktop_backends.pyindex 89390b344..011497905 100644--- a/tests/test_desktop_backends.py+++ b/tests/test_desktop_backends.py@@ -957,3 +957,178 @@ def test_an_installer_record_that_cannot_be_read_is_unknown_and_kept(monkeypatchassert refused.value.code == "install_locked"assert record.exists()+++# --- Removal deletes the backends only once no installer can be writing (#2131) ---+++def _remove_backends(monkeypatch, capsys, env: dict[str, str]) -> tuple[int, dict | None]:+ """``vibe desktop remove-backends`` as the desktop runs it, with ``env``'s private paths."""++ from vibe import cli++ for key in (+ "AVIBE_DESKTOP_RUNTIME_ROOT",+ "VIBE_SHOW_RUNTIME_NODE_BIN",+ "AVIBE_DESKTOP_NPM_CLI",+ "AVIBE_DESKTOP_BACKENDS_ROOT",+ ):+ monkeypatch.setenv(key, env[key])+ monkeypatch.setattr(cli.sys, "argv", ["vibe", "desktop", "remove-backends"])+ monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: None)+ capsys.readouterr()+ with pytest.raises(SystemExit) as exited:+ cli.main()+ err = capsys.readouterr().err.strip().splitlines()+ return exited.value.code, json.loads(err[-1]) if err else None+++def _backend_files(env: dict[str, str]) -> set[str]:+ root = Path(env["AVIBE_DESKTOP_BACKENDS_ROOT"])+ # A claim leaves its lock file behind; that is not an install's file.+ return {str(path.relative_to(root)) for path in root.rglob("*") if path.name != ".install.lock"}+++def _published_backends(env: dict[str, str]) -> None:+ root = Path(env["AVIBE_DESKTOP_BACKENDS_ROOT"])+ for backend in ("claude", "codex", "opencode"):+ _write_native(root / backend / "releases" / "r1" / "bin" / backend)+ (root / backend / "current.json").write_text("{}", encoding="utf-8")++[email protected](os.name == "nt", reason="POSIX process groups")+def test_removal_reaps_an_abandoned_installer_before_it_deletes_the_backends(monkeypatch, capsys, installer_tree):+ env, wait_for_tree = installer_tree+ pids = _start_killed_owner(env, wait_for_tree)+ _published_backends(env)++ assert _remove_backends(monkeypatch, capsys, env) == (0, None)++ assert _running(pids) == []+ assert _install_records() == []+ assert not os.path.lexists(env["AVIBE_DESKTOP_BACKENDS_ROOT"])++[email protected](os.name == "nt", reason="POSIX process groups")+def test_removal_keeps_every_file_while_an_installer_cannot_be_shown_gone(monkeypatch, capsys, installer_tree):+ env, wait_for_tree = installer_tree+ _start_killed_owner(env, wait_for_tree)+ _published_backends(env)+ monkeypatch.setattr(desktop_backends, "reap_marked_processes", lambda *args, **kwargs: "unconfirmed")+ files = _backend_files(env)++ assert _remove_backends(monkeypatch, capsys, env) == (3, {"reason": "install_locked"})++ assert _backend_files(env) == files+ assert len(_install_records()) == 1+ assert _install_lock_is_free(env)+++def test_removal_deletes_nothing_while_any_backend_is_being_installed(+ monkeypatch, capsys, tmp_path, owner_runtime_id, children+):+ # The held root sorts last, so the ones before it are already claimed.+ env = _desktop_env(tmp_path)+ _published_backends(env)+ held = Path(env["AVIBE_DESKTOP_BACKENDS_ROOT"]) / "opencode" / ".install.lock"+ ready = tmp_path / "held"+ holder = (+ "import pathlib, sys, time\n"+ "from storage.lock import MigrationFileLock\n"+ "MigrationFileLock(pathlib.Path(sys.argv[1])).acquire()\n"+ "pathlib.Path(sys.argv[2]).touch()\n"+ "time.sleep(120)\n"+ )+ children.append(subprocess.Popen([sys.executable, "-c", holder, str(held), str(ready)], cwd=_REPO_ROOT))+ deadline = time.monotonic() + 15+ while not ready.exists():+ assert time.monotonic() < deadline, "lock holder did not start"+ time.sleep(0.05)+ monkeypatch.setattr(desktop_backends, "DESKTOP_BACKEND_REMOVAL_LOCK_TIMEOUT_SECONDS", 0.2)+ files = _backend_files(env)++ assert _remove_backends(monkeypatch, capsys, env) == (3, {"reason": "install_locked"})++ assert _backend_files(env) == files+ assert _install_lock_is_free(env)+++# An install's first steps, as `install_desktop_backend` takes them.+_LATE_INSTALL = """+import pathlib, sys+from vibe import desktop_backends+root = pathlib.Path(sys.argv[1])+try:+ desktop_backends._claim_backend_root(root, timeout_seconds=30)+except desktop_backends.DesktopBackendError as exc:+ print(exc.code, flush=True)+else:+ (root / ".staging-late").mkdir()+ print("installing", flush=True)+"""++[email protected](os.name == "nt", reason="POSIX file locks")+def test_an_install_waiting_on_a_removed_backend_refuses_once_it_gets_the_lock(+ monkeypatch, capsys, tmp_path, owner_runtime_id, children+):+ env = _desktop_env(tmp_path)+ _published_backends(env)+ backend = Path(env["AVIBE_DESKTOP_BACKENDS_ROOT"]) / "claude"+ lock_path = os.path.realpath(backend / ".install.lock")+ remove_path = desktop_backends._remove_path++ def remove_once_an_install_waits(path):+ # Every lock is held once removal starts deleting.+ if not children:+ waiter = subprocess.Popen(+ [sys.executable, "-c", _LATE_INSTALL, str(backend)], cwd=_REPO_ROOT, stdout=subprocess.PIPE, text=True+ )+ children.append(waiter)+ deadline = time.monotonic() + 15+ while lock_path not in {os.path.realpath(f.path) for f in psutil.Process(waiter.pid).open_files()}:+ assert time.monotonic() < deadline, "the install did not wait on the lock"+ time.sleep(0.05)+ remove_path(path)++ monkeypatch.setattr(desktop_backends, "_remove_path", remove_once_an_install_waits)++ assert _remove_backends(monkeypatch, capsys, env) == (0, None)++ assert children[0].communicate(timeout=30)[0] == "install_locked\n"+ assert not os.path.lexists(env["AVIBE_DESKTOP_BACKENDS_ROOT"])+++def test_a_backend_an_install_begins_during_removal_keeps_its_files(monkeypatch, capsys, tmp_path, owner_runtime_id):+ env = _desktop_env(tmp_path)+ _published_backends(env)+ # A first install of a backend creates its directory after removal listed the root.+ late = Path(env["AVIBE_DESKTOP_BACKENDS_ROOT"]) / "late" / ".staging-late" / "package.json"+ remove_path = desktop_backends._remove_path++ def remove_once_an_install_began(path):+ if not late.exists():+ late.parent.mkdir(parents=True)+ late.write_text("{}", encoding="utf-8")+ remove_path(path)++ monkeypatch.setattr(desktop_backends, "_remove_path", remove_once_an_install_began)++ assert _remove_backends(monkeypatch, capsys, env) == (2, {"failed": "backend_removal_failed"})++ assert late.read_text(encoding="utf-8") == "{}"++[email protected](os.name == "nt" or os.geteuid() == 0, reason="POSIX file permissions")+def test_removal_that_cannot_delete_every_file_fails(monkeypatch, capsys, tmp_path, owner_runtime_id):+ env = _desktop_env(tmp_path)+ _published_backends(env)+ stuck = Path(env["AVIBE_DESKTOP_BACKENDS_ROOT"]) / "codex" / "releases"+ stuck.chmod(0o500)+ try:+ result = _remove_backends(monkeypatch, capsys, env)+ finally:+ stuck.chmod(0o700)++ assert result == (2, {"failed": "backend_removal_failed"})+ assert (stuck / "r1").is_dir()diff --git a/tests/test_desktop_runtime_stop.py b/tests/test_desktop_runtime_stop.pyindex 0bbe5d6b3..8f3fecd7d 100644--- a/tests/test_desktop_runtime_stop.py+++ b/tests/test_desktop_runtime_stop.py@@ -23,7 +23,8 @@ import psutilimport pytestfrom config import paths-from vibe import cli, desktop_backends, desktop_runtime, remote_access, runtime+from config.v2_config import V2Config+from vibe import cli, desktop_backends, desktop_runtime, remote_access, runtime, ui_server# Random, so no process another test file started with a fixed id is ever in scope.RUNTIME_ID = secrets.token_hex(32)@@ -54,7 +55,7 @@ def bundle(tmp_path) -> Path:(root / "bin").mkdir()(root / "bin" / "opencode").write_text(SLEEP + "\n", encoding="utf-8")(root / "serve").write_text(SLEEP + "\n", encoding="utf-8")- for name in ("node", "opencode", "my-opencode"):+ for name in ("node", "opencode", "my-opencode", "cloudflared"):(root / name).symlink_to(sys.executable)return root@@ -70,6 +71,7 @@ def argv_for(bundle):"opencode": [str(bundle / "node"), str(bundle / "bin" / "opencode"), *OPENCODE_SERVE],"opencode-native": [str(bundle / "opencode"), *OPENCODE_SERVE],"opencode-configured": [str(bundle / "my-opencode"), *OPENCODE_SERVE],+ "connector": [str(bundle / "cloudflared"), "-c", SLEEP, "tunnel", "run"],# Other programs whose command lines only mention a role."ui-lookalike": [sys.executable, "-c", SLEEP, "vibe.ui_server", "run_ui_server"],"opencode-lookalike": [sys.executable, "-c", SLEEP, "opencode", "serve"],@@ -211,8 +213,8 @@ def test_the_service_ui_installer_and_opencode_carrying_the_id_are_all_stopped(sfor child in children:child.wait(timeout=10)assert (child.pid, signal.SIGTERM) in stop_env["signals"]- # The tunnel is not stopped through the connector's files; see the ledger.- assert stop_env["remote_access"] == []+ # With no service or UI of this home left, the tunnel connector stops too.+ assert stop_env["remote_access"] == [True]assert stop_env["status"] == [("stopped",)]@@ -378,24 +380,35 @@ def test_a_service_lock_this_runtime_is_not_shown_to_own_keeps_the_shared_statusassert runtime._try_lock_file(stack.enter_context(lock_path.open("w", encoding="utf-8")))else:lock_path.mkdir(parents=True)- assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID) == (0 if late_role is None else 2)+ # The successor still serves the tunnel; with no holder known, the+ # connector's stop cannot be shown safe, and fails.+ assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID) == (0 if (lock, late_role) == ("held", None) else 2)ui.wait(timeout=10)assert stop_env["status"] == []+ assert stop_env["remote_access"] == []@pytest.mark.parametrize("late_role", [None, "installer"])-def test_no_service_can_take_the_lock_before_the_stop_s_status_lands(spawn, stop_env, monkeypatch, late_role):+def test_no_service_can_take_the_lock_before_the_stop_s_connector_and_status_land(+ spawn, stop_env, monkeypatch, late_role+):# A successor's service that takes the lock right after the stop decides- # the status is its own would publish a status the stop then overwrites.+ # the status is its own would publish a status the stop then overwrites,+ # and its UI would reconcile a tunnel the stop then takes down.record = cli._write_status- lock_free_at_write: list[bool] = []+ lock_free_at: list[tuple[str, bool]] = []def write(*args, **kwargs):- lock_free_at_write.append(runtime.service_instance_lock_available()[0])+ lock_free_at.append(("status", runtime.service_instance_lock_available()[0]))record(*args, **kwargs)+ def stop_connector():+ lock_free_at.append(("connector", runtime.service_instance_lock_available()[0]))+ return {"ok": True}+monkeypatch.setattr(cli, "_write_status", write)+ monkeypatch.setattr(remote_access, "stop", stop_connector)ui = spawn(RUNTIME_ID, "ui")if late_role is not None:_after_first_scan(monkeypatch, lambda _found: spawn(RUNTIME_ID, late_role))@@ -404,7 +417,73 @@ def test_no_service_can_take_the_lock_before_the_stop_s_status_lands(spawn, stopui.wait(timeout=10)assert len(stop_env["status"]) == 1- assert lock_free_at_write == [False]+ # A failed stop leaves the connector to the Runtime still running.+ expected = [("connector", False), ("status", False)] if late_role is None else [("status", False)]+ assert lock_free_at == expected++[email protected]("keeper", ["keep_remote_access", "a_ui_of_this_home"])+def test_the_tunnel_connector_is_left_to_what_still_serves_it(spawn, stop_env, keeper):+ service = spawn(RUNTIME_ID)+ if keeper == "a_ui_of_this_home":+ # Whoever started it, a running UI of this home serves the tunnel.+ other_ui = spawn(None, "ui")+ paths.get_runtime_ui_pid_path().write_text(str(other_ui.pid), encoding="utf-8")++ assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID, keep_remote_access=keeper == "keep_remote_access") == 0++ service.wait(timeout=10)+ assert stop_env["remote_access"] == []+ assert stop_env["status"] == [("stopped",)]+++def _connector_stop_raises():+ raise RuntimeError("connector state unreadable")+++ "connector_stop", [lambda: {"ok": False, "error": "cloudflared_stop_failed"}, _connector_stop_raises]+)+def test_a_tunnel_connector_that_does_not_stop_fails_the_stop(spawn, stop_env, capsys, monkeypatch, connector_stop):+ ui = spawn(RUNTIME_ID, "ui")+ monkeypatch.setattr(remote_access, "stop", connector_stop)++ assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID) == 2++ ui.wait(timeout=10)+ lines = _stderr_lines(capsys)+ assert lines[-2] == "ERROR: The remote access tunnel could not be stopped."+ assert json.loads(lines[-1]) == {"failed": "remote_access", "remaining": []}+ assert stop_env["status"] == [("error", cli._STOP_FAILURES["remote_access"][1])]+++def test_quit_takes_the_tunnel_down_and_the_next_ui_start_brings_it_back(spawn, monkeypatch, capsys):+ # Quit and uninstall end with this stop. It stops the connector through its+ # own files and leaves remote access enabled, so the UI of the next launch+ # reconciles the tunnel back.+ config = V2Config.default()+ config.remote_access.vibe_cloud.enabled = True+ config.remote_access.vibe_cloud.tunnel_token = "tunnel-token"+ config.save()+ monkeypatch.setattr(remote_access, "_report_runtime_status_async", lambda *args, **kwargs: None)+ ui, connector = spawn(RUNTIME_ID, "ui"), spawn(RUNTIME_ID, "connector")+ remote_access._pid_path().write_text(str(connector.pid), encoding="utf-8")++ assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID) == 0++ ui.wait(timeout=10)+ connector.wait(timeout=10)+ assert not remote_access._pid_path().exists()+ # Started by the UI, the connector carries its id, and is gone on return.+ assert not [line for line in _stderr_lines(capsys) if "left_running" in line]+ relaunched = V2Config.load()+ assert relaunched.remote_access.vibe_cloud.enabled+ starts: list[V2Config] = []+ monkeypatch.setattr(remote_access, "start", lambda config=None: starts.append(config) or {"ok": True})++ ui_server._reconcile_remote_access_for_ui_start(relaunched)++ assert starts == [relaunched]def _lock_path_is_a_directory(monkeypatch):@@ -440,6 +519,7 @@ def test_with_nothing_running_and_a_free_lock_the_stop_succeeds(stop_env):assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID) == 0assert stop_env["signals"] == []+ assert stop_env["remote_access"] == [True]assert stop_env["status"] == [("stopped",)]diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.pyindex 459399731..9300f077a 100644--- a/tests/test_restart_supervisor.py+++ b/tests/test_restart_supervisor.py@@ -375,6 +375,114 @@ def test_restart_job_stops_and_starts_service(monkeypatch, tmp_path, scope, readassert "restart_total_seconds" in status["stage_durations"]+_DESKTOP_IDENTITY = (+ "AVIBE_DESKTOP_RUNTIME_ID",+ "AVIBE_DESKTOP_MANAGED_RUNTIME",+ "AVIBE_DESKTOP_SHELL",+ "AVIBE_DESKTOP_RUNTIME_ROOT",+ "AVIBE_DESKTOP_BACKENDS_ROOT",+ "AVIBE_DESKTOP_NPM_CLI",+)+++ ("replaced", "caller", "executable", "successor"),+ [+ # A terminal `vibe restart` of the bundle's own `vibe`.+ ("tagged", "untagged", "bundle", "tagged"),+ # The restart runs other code, which is not that Runtime.+ ("tagged", "untagged", "other", "untagged"),+ # The Runtime being replaced decides, not the caller.+ ("untagged", "tagged", "bundle", "untagged"),+ # With no Runtime process left to read, the caller's identity stands.+ (None, "tagged", "bundle", "tagged"),+ # The service pid now names an unrelated process; the UI still runs.+ ("tagged-ui", "untagged", "bundle", "tagged"),+ ],+)+def test_a_restart_relaunches_the_replaced_runtime_s_desktop_identity(+ monkeypatch, tmp_path, replaced, caller, executable, successor+):+ import subprocess+ from unittest import mock++ from vibe import install_generations++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))+ paths.ensure_data_dirs()+ bundle = tmp_path / "bundle"+ launch = {+ "AVIBE_DESKTOP_RUNTIME_ID": "a" * 64,+ "AVIBE_DESKTOP_MANAGED_RUNTIME": "1",+ "AVIBE_DESKTOP_SHELL": "1",+ "AVIBE_DESKTOP_RUNTIME_ROOT": str(bundle),+ "AVIBE_DESKTOP_BACKENDS_ROOT": str(tmp_path / "backends"),+ "AVIBE_DESKTOP_NPM_CLI": str(bundle / "tools" / "npm" / "bin" / "npm-cli.js"),+ "VIBE_SHOW_RUNTIME_NODE_BIN": str(bundle / "tools" / "bin" / "node"),+ "PATH": os.pathsep.join([str(bundle / "bin"), str(bundle / "tools" / "bin"), "/usr/bin", "/bin"]),+ "PYTHONDONTWRITEBYTECODE": "1",+ }+ terminal = {"PATH": "/usr/local/bin:/usr/bin:/bin", "PYTHONPATH": str(tmp_path / "caller-site")}+ processes = []+ # The fake successor service, 222, and the service lock's owner.+ alive, owners = {222}, {222}++ def spawn(env, *argv):+ runtime_env = {key: value for key, value in os.environ.items() if not key.startswith(("PYTHON", "AVIBE_DESKTOP"))}+ runtime_env.update(env)+ process = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)", *argv], env=runtime_env)+ processes.append(process)+ alive.add(process.pid)+ return process.pid++ if replaced in ("tagged", "untagged"):+ service = spawn(launch if replaced == "tagged" else terminal)+ owners.add(service)+ paths.get_runtime_pid_path().write_text(str(service), encoding="utf-8")+ elif replaced == "tagged-ui":+ paths.get_runtime_pid_path().write_text(str(spawn(terminal)), encoding="utf-8")+ ui = spawn(launch, "vibe.ui_server", "run_ui_server")+ paths.get_runtime_ui_pid_path().write_text(str(ui), encoding="utf-8")+ python = bundle / "python" / "bin" / "python3" if executable == "bundle" else tmp_path / "other" / "python3"+ monkeypatch.setattr(sys, "executable", str(python))+ calls = []+ relaunched = {}++ def start(start_ui=True):+ 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, "_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)+ monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)+ # Holding the service lock is what makes a live pid the service.+ monkeypatch.setattr(runtime, "service_lock_held_by", lambda pid: pid in owners)+ monkeypatch.setattr(runtime, "wait_for_service_ready", lambda *args, **kwargs: 222)+ monkeypatch.setattr(install_generations, "collect_install_generations", lambda launcher: None)+ try:+ with mock.patch.dict(os.environ):+ for key in (*_DESKTOP_IDENTITY, "PYTHONDONTWRITEBYTECODE"):+ os.environ.pop(key, None)+ os.environ.update(launch if caller == "tagged" else terminal)+ rc = restart_supervisor._run_restart_job(job_id="jobidentity", delay_seconds=0, vibe_path=None, trigger="test")+ finally:+ for process in processes:+ process.kill()+ process.wait()++ assert rc == 0+ assert calls == ["stop_runtime", "start_runtime"]+ if successor == "tagged":+ for key, value in launch.items():+ assert relaunched.get(key) == value, key+ # The terminal's interpreter settings would put other code on the path.+ assert "PYTHONPATH" not in relaunched+ else:+ assert not set(_DESKTOP_IDENTITY) & set(relaunched)++def test_restart_job_uses_lock_holder_when_pidfile_is_missing(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))paths.ensure_data_dirs()diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.pyindex 182aa4009..4f454b286 100644--- a/tests/test_vibe_cli.py+++ b/tests/test_vibe_cli.py@@ -4334,7 +4334,11 @@ def test_start_parser_accepts_no_open_browser():[(["stop"], {}),(["stop", "--receipt", json.dumps(_startup_receipt_payload())], {"receipt": json.dumps(_startup_receipt_payload())}),- (["stop", "--expect-runtime-id", "a" * 64], {"expect_runtime_id": "a" * 64}),+ (["stop", "--expect-runtime-id", "a" * 64], {"expect_runtime_id": "a" * 64, "keep_remote_access": False}),+ (+ ["stop", "--expect-runtime-id", "a" * 64, "--keep-remote-access"],+ {"expect_runtime_id": "a" * 64, "keep_remote_access": True},+ ),],)def test_stop_parser_and_main_route_each_stop_mode(monkeypatch, arguments, expected):@@ -4357,6 +4361,20 @@ def test_stop_parser_rejects_a_receipt_with_an_expected_runtime_id():)+def test_only_a_scoped_stop_can_keep_remote_access(monkeypatch):+ # A full stop always stops the tunnel with the UI.+ calls = []+ monkeypatch.setattr(cli.sys, "argv", ["vibe", "stop", "--keep-remote-access"])+ monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: None)+ monkeypatch.setattr(cli, "cmd_stop", lambda **kwargs: calls.append(kwargs) or 0)++ with pytest.raises(SystemExit) as exited:+ cli.main()++ assert exited.value.code == 2+ assert calls == []++def test_remote_parser_accepts_pairing_command():parser = cli.build_parser()args = parser.parse_args(["remote", "pair", "vrp_test", "--device-name", "Mac Studio"])diff --git a/vibe/cli.py b/vibe/cli.pyindex 30be6ee4c..0919b9bab 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -13852,6 +13852,23 @@ def cmd_desktop_endpoint() -> int:return 0+def cmd_desktop_remove_backends() -> int:+ """Delete the desktop's backend installs: 3 while an install holds them, 2 when part may remain."""++ from vibe.desktop_backends import DesktopBackendError, remove_desktop_backends++ try:+ remove_desktop_backends()+ except DesktopBackendError as exc:+ logger.error("Desktop backend removal failed: %s", exc)+ if exc.code == "install_locked":+ _print_stop_json({"reason": exc.code})+ return 3+ _print_stop_json({"failed": exc.code})+ return 2+ return 0++def cmd_vibe():"""Compatibility default: bare `vibe` starts services and opens the Web UI."""return cmd_start()@@ -13937,6 +13954,7 @@ _STOP_FAILURES = {"installer": ("runtime.stop.installerFailed", "desktop backend install drain failed"),"opencode": ("runtime.stop.opencodeFailed", "opencode stop failed"),"unknown": ("runtime.stop.unknownFailed", "unidentified runtime process left running"),+ "remote_access": ("runtime.stop.remoteAccessFailed", "remote access stop failed"),}@@ -13962,30 +13980,66 @@ def _print_stop_json(payload: dict) -> None:print(json.dumps(payload, separators=(",", ":")), file=sys.stderr)-def _stop_expected_desktop_runtime(runtime_id: str) -> int:+def _print_left_running(result: runtime.DesktopRuntimeStopResult) -> None:+ # A tunnel connector started by a desktop UI inherits its Runtime id, so+ # the scan may list it; what is reported is what still runs on return.+ left_running = [item for item in result.left_running if runtime.pid_alive(item.pid)]+ if left_running:+ _print_stop_json({"left_running": [{"pid": item.pid, "name": item.name} for item in left_running]})+++def _stop_expected_desktop_runtime(runtime_id: str, *, keep_remote_access: bool = False) -> int:result = runtime.stop_desktop_runtime(runtime_id)if result.outcome is runtime.DesktopRuntimeStopOutcome.NOT_OURS:_print_stop_json({"reason": result.refusal})return 3- if result.left_running:- _print_stop_json({"left_running": [{"pid": item.pid, "name": item.name} for item in result.left_running]})if result.opencode_stopped:_report_opencode_stopped()# Unlike a full stop, an OpenCode server of this Runtime that survives# fails this stop: the desktop host replaces or removes the bundle it runs from.if result.outcome is runtime.DesktopRuntimeStopOutcome.FAILED:+ _print_left_running(result)status = _stop_failed(result.failure, _write_status_unless_a_service_holds_the_lock)remaining = [{"pid": item.pid, "role": item.role} for item in result.remaining]_print_stop_json({"failed": result.failure, "remaining": remaining})return status+ if keep_remote_access:+ _write_status_unless_a_service_holds_the_lock("stopped")+ status = 0+ else:+ status = _stop_the_home_s_connector()+ _print_left_running(result)+ if status:+ _print_stop_json({"failed": "remote_access", "remaining": []})+ return status+++def _stop_the_home_s_connector() -> int:+ # The tunnel connector serves this home's Web UI, whichever Runtime+ # started it. It stops only while this stop holds the free service lock,+ # so no service can run, and no UI of this home is left to serve it.+ outcome: list[int] = []++ def settle_the_connector() -> None:+ if runtime.ui_pid_file_points_to_running_ui() or runtime.stop_remote_access_connector():+ _write_status("stopped")+ outcome.append(0)+ else:+ outcome.append(_stop_failed("remote_access"))- _write_status_unless_a_service_holds_the_lock("stopped")- return 0+ presence = runtime.desktop_service_lock_presence(while_absent=settle_the_connector)+ # The service holding the lock still owns the connector, and the status.+ if presence is runtime.DesktopRuntimePresence.MISMATCH or outcome == [0]:+ return 0+ if not outcome:+ # No free lock showed that no service still needs the connector.+ outcome.append(_stop_failed("remote_access", _write_status_unless_a_service_holds_the_lock))+ return outcome[0]-def cmd_stop(*, receipt: str | None = None, expect_runtime_id: str | None = None):+def cmd_stop(*, receipt: str | None = None, expect_runtime_id: str | None = None, keep_remote_access: bool = False):if expect_runtime_id is not None:- return _stop_expected_desktop_runtime(expect_runtime_id)+ return _stop_expected_desktop_runtime(expect_runtime_id, keep_remote_access=keep_remote_access)if receipt is not None:reason = _stop_receipt_refusal(receipt)if reason is not None:@@ -16595,6 +16649,11 @@ def build_parser():metavar="RUNTIME_ID",help="Stop only the processes the desktop Runtime with this id started.",)+ stop_parser.add_argument(+ "--keep-remote-access",+ action="store_true",+ help="With --expect-runtime-id, leave the remote access tunnel running.",+ )start_parser = subparsers.add_parser("start", help="Start services if needed without stopping running processes")start_parser.add_argument("--no-open-browser",@@ -16612,6 +16671,7 @@ def build_parser():desktop_subparsers = desktop_parser.add_subparsers(dest="desktop_command", required=True)desktop_endpoint_parser = desktop_subparsers.add_parser("endpoint", help=argparse.SUPPRESS)desktop_endpoint_parser.add_argument("--json", action="store_true", required=True, help=argparse.SUPPRESS)+ desktop_subparsers.add_parser("remove-backends", help=argparse.SUPPRESS)restart_parser = subparsers.add_parser("restart", help="Restart all services")restart_parser.add_argument("--delay-seconds",@@ -18502,6 +18562,7 @@ _CLI_COMMAND_FLOORS: dict[tuple[str, ...], Optional[str]] = {("check-update",): None,("status",): None,("desktop", "endpoint"): "member",+ ("desktop", "remove-backends"): "member",# Host scope, not instance scope: these act on this machine's screen and on# authored files, and have no role contract to repair here.("screenshot",): None,@@ -18738,10 +18799,14 @@ def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:"""Run the admitted command. Every branch exits; nothing returns to ``main``."""if args.command == "stop":+ if args.keep_remote_access and args.expect_runtime_id is None:+ parser.error("--keep-remote-access requires --expect-runtime-id")if args.receipt is not None:sys.exit(cmd_stop(receipt=args.receipt))if args.expect_runtime_id is not None:- sys.exit(cmd_stop(expect_runtime_id=args.expect_runtime_id))+ sys.exit(+ cmd_stop(expect_runtime_id=args.expect_runtime_id, keep_remote_access=args.keep_remote_access)+ )sys.exit(cmd_stop())if args.command == "start":if _generation_downgrade_blocks("start", allow_downgrade=args.allow_downgrade):@@ -18749,6 +18814,8 @@ def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:sys.exit(cmd_start(open_browser=args.open_browser))if args.command == "desktop" and args.desktop_command == "endpoint":sys.exit(cmd_desktop_endpoint())+ if args.command == "desktop" and args.desktop_command == "remove-backends":+ sys.exit(cmd_desktop_remove_backends())if args.command == "restart":if _generation_downgrade_blocks("restart", allow_downgrade=args.allow_downgrade):sys.exit(1)diff --git a/vibe/desktop_backends.py b/vibe/desktop_backends.pyindex 937000e15..b82bdc662 100644--- a/vibe/desktop_backends.py+++ b/vibe/desktop_backends.py@@ -61,6 +61,9 @@ MAX_DESCRIPTOR_BYTES = 16 * 1024MAX_INSTALL_OUTPUT_CHARS = 8192NPM_REGISTRY = "https://registry.npmjs.org/"DESKTOP_BACKEND_LOCK_TIMEOUT_SECONDS = 30.0+# Removal runs once the Runtime has stopped, when no install should be left to+# wait for.+DESKTOP_BACKEND_REMOVAL_LOCK_TIMEOUT_SECONDS = 5.0DESKTOP_BACKEND_INSTALL_TIMEOUT_SECONDS = 300.0DESKTOP_BACKEND_PROBE_TIMEOUT_SECONDS = 15.0DESKTOP_BACKEND_PROCESS_DRAIN_TIMEOUT_SECONDS = 10.0@@ -929,10 +932,24 @@ def _claim_backend_root(backend_root: Path, *, timeout_seconds: float) -> Migratfirst; its tree is reaped by its marker and its staging removed. When therecords cannot be listed or read, nothing is removed; then, or when atree cannot be shown gone, the lock is released and ``install_locked``- raised.+ raised. So is it when removal deleted the lock file while this waited."""- lock = MigrationFileLock(backend_root / ".install.lock", timeout_seconds=timeout_seconds)+ lock_path = backend_root / ".install.lock"+ removed: list[bool] = []++ def names_the_lock_path(handle) -> bool:+ # Removal deletes a lock file while it holds it, so a waiter that gets+ # the lock then holds a file no other install would lock.+ try:+ same = os.path.samestat(os.fstat(handle.fileno()), os.stat(lock_path))+ except FileNotFoundError:+ same = False+ if not same:+ removed.append(True)+ return same++ lock = MigrationFileLock(lock_path, timeout_seconds=timeout_seconds, _handle_validator=names_the_lock_path)try:lock.acquire()except MigrationLockTimeout as exc:@@ -940,6 +957,13 @@ def _claim_backend_root(backend_root: Path, *, timeout_seconds: float) -> Migratf"Another {backend_root.name} install is already running.",code="install_locked",) from exc+ except OSError as exc:+ if not removed:+ raise+ raise DesktopBackendError(+ f"The {backend_root.name} backend directory is being removed.",+ code="install_locked",+ ) from exctry:records = [record for record in _installer_records() if record.backend_root == backend_root]settled = reap_abandoned_desktop_backend_installs() and all(@@ -963,6 +987,66 @@ def _claim_backend_root(backend_root: Path, *, timeout_seconds: float) -> Migratreturn lock+def remove_desktop_backends(base_env: Mapping[str, str] | None = None) -> None:+ """Delete the app-private backend root once no installer can be writing into it.++ Every backend directory is claimed the way an install claims it, which+ reaps the installer trees abandoned in it, and nothing is deleted until all+ of them are held. Nothing is deleted recursively once a lock is released,+ so an install that begins meanwhile keeps its files, and fails the+ removal. Raises ``DesktopBackendError``: ``install_locked`` with nothing+ deleted, and any other code when part of the root may remain.+ """++ root = private_desktop_backends_root(base_env)+ if root is None:+ raise DesktopBackendError("The desktop backend root is unavailable.", code="invalid_backend_root")+ if not os.path.lexists(root):+ return+ if root.is_symlink() or not root.is_dir():+ raise DesktopBackendError("Invalid desktop backend root.", code="invalid_backend_root")+ claimed: list[tuple[Path, MigrationFileLock]] = []+ try:+ try:+ entries = sorted(root.iterdir())+ for entry in entries:+ if entry.is_dir() and not entry.is_symlink():+ lock = _claim_backend_root(entry, timeout_seconds=DESKTOP_BACKEND_REMOVAL_LOCK_TIMEOUT_SECONDS)+ claimed.append((entry, lock))+ for entry in entries:+ if entry.is_dir() and not entry.is_symlink():+ for member in entry.iterdir():+ if member.name != ".install.lock":+ _remove_path(member)+ else:+ _remove_path(entry)+ for entry, lock in claimed:+ # A waiter that then gets the lock finds its file gone, and+ # refuses. Windows deletes no open file, so the lock file goes+ # once released, and stays while any installer has it open.+ if os.name == "nt":+ lock.release()+ (entry / ".install.lock").unlink(missing_ok=True)+ entry.rmdir()+ # A directory an install created since the listing keeps the root.+ root.rmdir()+ finally:+ for _entry, lock in reversed(claimed):+ lock.release()+ except OSError as exc:+ raise DesktopBackendError(+ f"The desktop backend root could not be removed: {exc}",+ code="backend_removal_failed",+ ) from exc+++def _remove_path(path: Path) -> None:+ if path.is_dir() and not path.is_symlink():+ shutil.rmtree(path)+ else:+ path.unlink(missing_ok=True)++def _installed_package_version(package_dir: Path, expected_package: str) -> str:manifest = package_dir / "package.json"try:diff --git a/vibe/desktop_runtime.py b/vibe/desktop_runtime.pyindex c1a773445..59cbe4769 100644--- a/vibe/desktop_runtime.py+++ b/vibe/desktop_runtime.py@@ -23,6 +23,8 @@ DESKTOP_RUNTIME_ROOT_ENV = "AVIBE_DESKTOP_RUNTIME_ROOT"DESKTOP_NODE_BIN_ENV = "VIBE_SHOW_RUNTIME_NODE_BIN"DESKTOP_NPM_CLI_ENV = "AVIBE_DESKTOP_NPM_CLI"DESKTOP_BACKENDS_ROOT_ENV = "AVIBE_DESKTOP_BACKENDS_ROOT"+# Set by the desktop launcher on every Runtime it starts; no code branches on it.+DESKTOP_SHELL_ENV = "AVIBE_DESKTOP_SHELL"# Every process a backend install starts carries this, so a process scan tells# an installer tree from the other programs that carry the Runtime id.DESKTOP_ROLE_ENV = "AVIBE_DESKTOP_ROLE"diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 3838788aa..e6cadd5c4 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -1083,7 +1083,8 @@"uiFailed": "ERROR: Avibe UI did not stop; preserving pidfile and aborting.","installerFailed": "ERROR: Desktop backend installer processes did not stop.","opencodeFailed": "ERROR: The OpenCode server this Runtime started did not stop.",- "unknownFailed": "ERROR: A process this Runtime started could not be identified and was left running."+ "unknownFailed": "ERROR: A process this Runtime started could not be identified and was left running.",+ "remoteAccessFailed": "ERROR: The remote access tunnel could not be stopped."}},"doctor": {diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 937d0b3ab..a014da29e 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -1083,7 +1083,8 @@"uiFailed": "错误:Avibe UI 未能停止;已保留 pidfile 并中止。","installerFailed": "错误:桌面后端安装进程未能停止。","opencodeFailed": "错误:此 Runtime 启动的 OpenCode 服务未能停止。",- "unknownFailed": "错误:此 Runtime 启动的一个进程无法识别,已保留运行。"+ "unknownFailed": "错误:此 Runtime 启动的一个进程无法识别,已保留运行。",+ "remoteAccessFailed": "错误:远程访问隧道无法停止。"}},"doctor": {diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.pyindex 9e045a91e..835f783cc 100644--- a/vibe/restart_supervisor.py+++ b/vibe/restart_supervisor.py@@ -4,16 +4,31 @@ import argparseimport loggingimport osimport subprocess+import sysimport timeimport uuid+from collections.abc import Mappingfrom concurrent.futures import ThreadPoolExecutorfrom pathlib import Pathfrom typing import NamedTuple+import psutil+from config import pathsfrom core.process_isolation import isolated_subprocess_kwargsfrom vibe import runtime+from vibe.desktop_runtime import (+ DESKTOP_BACKENDS_ROOT_ENV,+ DESKTOP_NODE_BIN_ENV,+ DESKTOP_NPM_CLI_ENV,+ DESKTOP_RUNTIME_ID_ENV,+ DESKTOP_RUNTIME_ROOT_ENV,+ DESKTOP_SHELL_ENV,+ desktop_runtime_id,+ is_private_desktop_runtime_path,+)from vibe.upgrade import (+ DESKTOP_MANAGED_RUNTIME_ENV,RestartState,atomic_upgrade_lock,get_restart_command,@@ -26,6 +41,18 @@ from vibe.upgrade import (logger = logging.getLogger(__name__)_RESTART_LOG_RETENTION = 10_SERVICE_LOCK_RELEASE_TIMEOUT_SECONDS = 30.0+# What the desktop launcher stamps on a Runtime it starts. The launch set adds+# what that Runtime resolves its own tools through; the interpreter's `PYTHON*`+# settings travel with it too.+_DESKTOP_IDENTITY_ENV = (+ DESKTOP_RUNTIME_ID_ENV,+ DESKTOP_MANAGED_RUNTIME_ENV,+ DESKTOP_SHELL_ENV,+ DESKTOP_RUNTIME_ROOT_ENV,+ DESKTOP_BACKENDS_ROOT_ENV,+ DESKTOP_NPM_CLI_ENV,+)+_DESKTOP_LAUNCH_ENV = (*_DESKTOP_IDENTITY_ENV, DESKTOP_NODE_BIN_ENV, "PATH")class StartedRuntime(NamedTuple):@@ -143,6 +170,57 @@ def _read_recorded_ui_pid() -> int | None:return pid if pid > 0 else None+def _replaced_runtime_environ() -> Mapping[str, str] | None:+ """The environment of the Runtime this job replaces, when one of its processes can be read.++ A recorded pid names that Runtime only while it still runs its role: the+ service is the service lock's owner, and the UI runs the UI server. A pid+ an unrelated process has reused is passed over.+ """++ service_pid = _read_recorded_pid()+ if service_pid and not runtime.service_lock_held_by(service_pid):+ service_pid = None+ ui_pid = _read_recorded_ui_pid() if runtime.ui_pid_file_points_to_running_ui() else None+ for pid in (service_pid, ui_pid):+ if not pid:+ continue+ try:+ return psutil.Process(pid).environ()+ except (psutil.Error, OSError):+ continue+ return None+++def _carry_desktop_identity() -> str:+ """Give the successor the replaced Runtime's desktop identity when it runs the same bundle.++ The identity lives only in the Runtime's environment, and this job inherits+ its caller's: a restart from a terminal would drop it, and the desktop would+ find an unmanaged Runtime. So it is read from the Runtime being replaced, or+ from this job's own environment when none of its processes is left to read.+ Only a successor started from that Runtime's own bundle carries it, with the+ rest of its launch set; other code is not that Runtime, and carries none.+ """++ source = _replaced_runtime_environ()+ if source is None:+ source = dict(os.environ)+ runtime_id = desktop_runtime_id(source)+ if runtime_id is None or not is_private_desktop_runtime_path(sys.executable, source):+ for key in _DESKTOP_IDENTITY_ENV:+ os.environ.pop(key, None)+ return "without a desktop identity"+ python_settings = {key for key in (*source, *os.environ) if key.startswith("PYTHON")}+ for key in (*_DESKTOP_LAUNCH_ENV, *sorted(python_settings)):+ value = source.get(key)+ if value is None:+ os.environ.pop(key, None)+ else:+ os.environ[key] = value+ return f"as desktop Runtime {runtime_id}"++def _remaining_service_pids_after_stop() -> list[int]:owner_pid = runtime.resolve_service_owner_pid(include_starting=True)pids: list[int] = []@@ -353,6 +431,7 @@ def _run_restart_job(write("restart job started after delay")restart_started_at = time.monotonic()+ 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:diff --git a/vibe/runtime.py b/vibe/runtime.pyindex 051080e0c..b80e1f7d7 100644--- a/vibe/runtime.py+++ b/vibe/runtime.py@@ -2515,25 +2515,34 @@ def stop_service():return stopped_all+def stop_remote_access_connector() -> bool:+ """Stop this home's tunnel connector; ``False`` when it may still be running.++ The connector's configuration is left as it is, so the next UI start+ reconciles it back when remote access is enabled.+ """++ try:+ from vibe import remote_access++ result = remote_access.stop()+ except Exception:+ logger.warning("Failed to stop remote access", exc_info=True)+ return False+ if isinstance(result, dict) and result.get("ok") is False:+ logger.warning("Failed to stop remote access: %s", result.get("error"))+ return False+ return True++def stop_ui(timings: dict[str, float | bool] | None = None, *, stop_remote_access: bool = True):remote_access_stopped = Truestarted_at = time.monotonic()if stop_remote_access:remote_access_started_at = time.monotonic()- try:- from vibe import remote_access-- result = remote_access.stop()- if timings is not None:- timings["stop_remote_access_seconds"] = _rounded_seconds(time.monotonic() - remote_access_started_at)- if isinstance(result, dict) and result.get("ok") is False:- logger.warning("Failed to stop remote access before UI stop: %s", result.get("error"))- remote_access_stopped = False- except Exception:- if timings is not None and "stop_remote_access_seconds" not in timings:- timings["stop_remote_access_seconds"] = _rounded_seconds(time.monotonic() - remote_access_started_at)- logger.warning("Failed to stop remote access before UI stop", exc_info=True)- remote_access_stopped = False+ remote_access_stopped = stop_remote_access_connector()+ if timings is not None:+ timings["stop_remote_access_seconds"] = _rounded_seconds(time.monotonic() - remote_access_started_at)elif timings is not None:timings["stop_remote_access_seconds"] = 0.0timings["stop_remote_access_skipped"] = True