Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(upgrade): report stable launcher activation failures (#2424)

Call White11bd36b1b82a
diff --git a/tests/test_install_generation_retirement.py b/tests/test_install_generation_retirement.py
index 5b080eb5f..d53bd3d41 100644
--- a/tests/test_install_generation_retirement.py
+++ b/tests/test_install_generation_retirement.py
@@ -757,9 +757,35 @@ def test_root_launchers_move_together_through_either_activation(installation, mo
assert os.readlink(foreign) == str(foreign_target)
+def test_alias_peer_that_reaches_primary_generation_is_not_reported_as_failed(
+ installation, monkeypatch, tmp_path,
+):
+ root, launcher = installation
+ peer = tmp_path / "alias-home" / ".local" / "bin" / "vibe"
+ peer.parent.mkdir(parents=True)
+ monkeypatch.setattr(upgrade, "INSTALLER_LAUNCHER_DIRS", (str(peer.parent),))
+ old = activate(root, launcher, "old")
+ peer.symlink_to(old)
+ current = candidate(root, "current")
+
+ def race_to_alias(_peer_launcher, _selected, _target):
+ peer.unlink()
+ peer.symlink_to(current)
+ return False
+
+ monkeypatch.setattr(upgrade, "move_managed_launcher_locked", race_to_alias)
+ outcome = upgrade.activate_installer_candidate(upgrade.AtomicActivation(
+ launcher, current, upgrade._launcher_generation(launcher, root),
+ ))
+
+ assert launcher.resolve() == current.resolve()
+ assert peer.resolve() == current.resolve()
+ assert outcome.peer_failures == ()
+
+
def test_a_launcher_that_cannot_move_keeps_its_generation(installation, monkeypatch, tmp_path):
root, launcher = installation
- peer = tmp_path / "root-home" / ".local" / "bin" / "vibe"
+ peer = tmp_path / "root home 空格" / ".local" / "bin" / "vibe"
peer.parent.mkdir(parents=True)
monkeypatch.setattr(upgrade, "INSTALLER_LAUNCHER_DIRS", (str(peer.parent),))
old = activate(root, launcher, "old")
@@ -769,12 +795,36 @@ def test_a_launcher_that_cannot_move_keeps_its_generation(installation, monkeypa
raise PermissionError(f"{path} is read-only")
monkeypatch.setattr(upgrade, "_activate_launcher_target_locked", read_only)
- current = activate(root, launcher, "current")
+ current = candidate(root, "current")
+ outcome = upgrade.activate_installer_candidate(upgrade.AtomicActivation(
+ launcher, current, upgrade._launcher_generation(launcher, root),
+ ))
assert launcher.resolve() == current.resolve()
assert peer.resolve() == old.resolve()
assert {path.name for path in root.iterdir()} == {"old", "current"}
assert subprocess.run([str(peer)], check=False).returncode == 0
+ assert outcome.activated_launcher == launcher.absolute()
+ assert [(failure.launcher, failure.reason) for failure in outcome.peer_failures] == [
+ (peer.absolute(), f"{peer} is read-only"),
+ ]
+ assert [failure.reason_code for failure in outcome.peer_failures] == ["permission_denied"]
+ for language, expected in (
+ ("en", "Upgrade activated the new version"),
+ ("zh", "升级已激活新版本"),
+ ):
+ notice = upgrade.format_activation_failures(outcome, language)
+ assert notice is not None
+ assert expected in notice
+ assert str(peer) in notice
+ assert "is read-only" in notice
+ assert "doctor repair stable-launchers" in notice
+ if language == "en":
+ assert "Correct its permissions or ownership first" in notice
+ assert "then run `" in notice
+ assert "then Run `" not in notice
+ else:
+ assert "先修正其权限或所有者" in notice
def test_a_peer_replaced_after_discovery_is_left_alone(installation, monkeypatch, tmp_path):
@@ -800,10 +850,31 @@ def test_a_peer_replaced_after_discovery_is_left_alone(installation, monkeypatch
return found
monkeypatch.setattr(upgrade, "managed_stable_launchers", replaced_after_discovery)
- current = activate(root, launcher, "current")
+ current = candidate(root, "current")
+ outcome = upgrade.activate_installer_candidate(upgrade.AtomicActivation(
+ launcher, current, upgrade._launcher_generation(launcher, root),
+ ))
assert launcher.resolve() == current.resolve()
assert os.readlink(peer) == str(foreign_target)
+ assert [(failure.launcher, failure.reason) for failure in outcome.peer_failures] == [
+ (peer.absolute(), "the launcher changed after discovery"),
+ ]
+ assert [failure.reason_code for failure in outcome.peer_failures] == ["launcher_changed_after_discovery"]
+ notice_en = upgrade.format_activation_failures(outcome, "en")
+ notice_zh = upgrade.format_activation_failures(outcome, "zh")
+ assert notice_en is not None
+ assert notice_zh is not None
+ assert "the launcher changed after discovery" not in notice_zh
+ assert "so it was left untouched" in notice_en
+ assert "Inspect that launcher and confirm its intended target or installation" in notice_en
+ assert "other remaining managed stable launchers" in notice_en
+ assert "发现后发生了变化" in notice_zh
+ assert "因此该启动器保持原样" in notice_zh
+ assert "请检查该启动器并确认其目标或安装状态" in notice_zh
+ assert "其他仍受管理的稳定启动器" in notice_zh
+ assert "doctor repair stable-launchers" in notice_en
+ assert "doctor repair stable-launchers" in notice_zh
def test_partial_removal_retains_uv_evidence_and_next_pass_finishes(installation, monkeypatch):
@@ -904,6 +975,288 @@ def test_installer_diagnostics_restore_logging_without_a_traceback(
assert retention.logger.level == level
+def test_installer_postcommit_notice_failure_keeps_committed_generation(
+ installation, monkeypatch,
+):
+ from vibe import cli
+
+ root, launcher = installation
+ exported = candidate(root, "selected")
+ monkeypatch.setattr(
+ cli,
+ "format_activation_failures",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(BrokenPipeError("closed pipe")),
+ )
+
+ result = cli._dispatch_installer_activation([
+ "--launcher", str(launcher), "--candidate", str(exported),
+ ])
+
+ assert result == 0
+ assert launcher.resolve() == exported.resolve()
+ assert exported.exists()
+ assert (root / "selected").exists()
+
+
+def test_installer_postcommit_owner_failure_keeps_committed_generation(
+ installation, monkeypatch,
+):
+ from vibe import cli
+
+ root, launcher = installation
+ exported = candidate(root, "selected")
+ activate = cli.activate_installer_candidate
+
+ def activate_then_fail(activation):
+ activate(activation)
+ raise RuntimeError("retention reporting failed")
+
+ monkeypatch.setattr(cli, "activate_installer_candidate", activate_then_fail)
+
+ result = cli._dispatch_installer_activation([
+ "--launcher", str(launcher), "--candidate", str(exported),
+ ])
+
+ assert result == 0
+ assert launcher.resolve() == exported.resolve()
+ assert exported.exists()
+ assert (root / "selected").exists()
+
+
+def test_cli_postcommit_notice_failure_keeps_committed_generation(
+ installation, monkeypatch, capsys,
+):
+ from vibe import cli
+
+ root, launcher = installation
+ exported = candidate(root, "selected")
+ plan = upgrade.UpgradePlan(
+ command=["uv-fixture"],
+ env=None,
+ method="uv",
+ activation=upgrade.AtomicActivation(launcher, exported),
+ )
+ monkeypatch.setattr(
+ cli,
+ "get_latest_version",
+ lambda: {"error": None, "has_update": True, "latest": "99"},
+ )
+ monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: str(launcher))
+ monkeypatch.setattr(cli, "build_upgrade_plan", lambda **_kwargs: plan)
+ monkeypatch.setattr(cli, "_runtime_process_was_running", lambda: False)
+ monkeypatch.setattr(
+ cli,
+ "execute_upgrade_plan",
+ lambda *_args, **_kwargs: subprocess.CompletedProcess(plan.command, 0, "", ""),
+ )
+ monkeypatch.setattr(cli, "_prepare_show_runtime_after_install", lambda *_args: None)
+ monkeypatch.setattr(
+ cli,
+ "format_activation_failures",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("notice failed")),
+ )
+
+ result = cli.cmd_upgrade()
+
+ assert result == 0
+ assert "Stable launcher activation notice unavailable: notice failed" in capsys.readouterr().out
+ assert launcher.resolve() == exported.resolve()
+ assert exported.exists()
+ assert (root / "selected").exists()
+
+
+def test_cli_postcommit_owner_failure_keeps_committed_generation(
+ installation, monkeypatch, capsys,
+):
+ from vibe import cli
+
+ root, launcher = installation
+ exported = candidate(root, "selected")
+ plan = upgrade.UpgradePlan(
+ command=["uv-fixture"],
+ env=None,
+ method="uv",
+ activation=upgrade.AtomicActivation(launcher, exported),
+ )
+ monkeypatch.setattr(
+ cli,
+ "get_latest_version",
+ lambda: {"error": None, "has_update": True, "latest": "99"},
+ )
+ monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: str(launcher))
+ monkeypatch.setattr(cli, "build_upgrade_plan", lambda **_kwargs: plan)
+ monkeypatch.setattr(cli, "_runtime_process_was_running", lambda: False)
+ monkeypatch.setattr(
+ cli,
+ "execute_upgrade_plan",
+ lambda *_args, **_kwargs: subprocess.CompletedProcess(plan.command, 0, "", ""),
+ )
+ monkeypatch.setattr(cli, "_prepare_show_runtime_after_install", lambda *_args: None)
+ activate = cli.activate_upgrade_candidate
+
+ def activate_then_fail(activation):
+ activate(activation)
+ raise RuntimeError("retention reporting failed")
+
+ monkeypatch.setattr(cli, "activate_upgrade_candidate", activate_then_fail)
+
+ result = cli.cmd_upgrade()
+
+ assert result == 0
+ assert "post-activation cleanup reported" in capsys.readouterr().out
+ assert launcher.resolve() == exported.resolve()
+ assert exported.exists()
+ assert (root / "selected").exists()
+
+
+def test_api_postcommit_notice_failure_keeps_committed_generation(
+ installation, monkeypatch,
+):
+ from vibe import api
+
+ root, launcher = installation
+ exported = candidate(root, "selected")
+ plan = upgrade.UpgradePlan(
+ command=["uv-fixture"],
+ env=None,
+ method="uv",
+ activation=upgrade.AtomicActivation(launcher, exported),
+ )
+ monkeypatch.setattr(api, "get_version_info", lambda: {"latest": "99"})
+ monkeypatch.setattr(api, "get_running_vibe_path", lambda: str(launcher))
+ monkeypatch.setattr(api, "build_upgrade_plan", lambda **_kwargs: plan)
+ monkeypatch.setattr(api, "_runtime_process_was_running", lambda: True)
+ restart_calls = []
+ monkeypatch.setattr(api, "schedule_restart", lambda **kwargs: restart_calls.append(kwargs) or {"job_id": "restart"})
+ monkeypatch.setattr(
+ api,
+ "execute_upgrade_plan",
+ lambda *_args, **_kwargs: subprocess.CompletedProcess(plan.command, 0, "", ""),
+ )
+ monkeypatch.setattr(api, "_prepare_show_runtime_after_upgrade", lambda *_args: None)
+ monkeypatch.setattr(
+ api,
+ "format_activation_failures",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("notice failed")),
+ )
+
+ result = api.do_upgrade(auto_restart=True)
+
+ assert result["ok"] is True
+ assert result["message"] == "Upgrade successful. Restarting..."
+ assert result["activation_notice"] is None
+ assert result["output"] == "Stable launcher activation notice unavailable: notice failed"
+ assert result["restarting"] is True
+ assert restart_calls
+ assert launcher.resolve() == exported.resolve()
+ assert exported.exists()
+ assert (root / "selected").exists()
+
+
+def test_api_postcommit_owner_failure_keeps_committed_generation(
+ installation, monkeypatch,
+):
+ from vibe import api
+
+ root, launcher = installation
+ exported = candidate(root, "selected")
+ plan = upgrade.UpgradePlan(
+ command=["uv-fixture"],
+ env=None,
+ method="uv",
+ activation=upgrade.AtomicActivation(launcher, exported),
+ )
+ monkeypatch.setattr(api, "get_version_info", lambda: {"latest": "99"})
+ monkeypatch.setattr(api, "get_running_vibe_path", lambda: str(launcher))
+ monkeypatch.setattr(api, "build_upgrade_plan", lambda **_kwargs: plan)
+ monkeypatch.setattr(api, "_runtime_process_was_running", lambda: False)
+ monkeypatch.setattr(
+ api,
+ "execute_upgrade_plan",
+ lambda *_args, **_kwargs: subprocess.CompletedProcess(plan.command, 0, "", ""),
+ )
+ monkeypatch.setattr(api, "_prepare_show_runtime_after_upgrade", lambda *_args: None)
+ activate = api.activate_upgrade_candidate
+
+ def activate_then_fail(activation):
+ activate(activation)
+ raise RuntimeError("retention reporting failed")
+
+ monkeypatch.setattr(api, "activate_upgrade_candidate", activate_then_fail)
+
+ result = api.do_upgrade(auto_restart=False)
+
+ assert result["ok"] is True
+ assert result["message"] == "Upgrade successful. Please restart vibe."
+ assert result["output"] == "Upgrade activation cleanup reported: retention reporting failed"
+ assert result["restarting"] is False
+ assert launcher.resolve() == exported.resolve()
+ assert exported.exists()
+ assert (root / "selected").exists()
+
+
[email protected]("failure", ["metadata", "format"])
+def test_deferred_parent_posthandoff_diagnostic_failure_keeps_generation(
+ installation, monkeypatch, failure,
+):
+ from vibe import api
+
+ root, launcher = installation
+ exported = candidate(root, "deferred")
+ plan = upgrade.UpgradePlan(
+ command=["uv-fixture"],
+ env=None,
+ method="uv",
+ activation=upgrade.AtomicActivation(launcher, exported),
+ )
+
+ class WindowsOsProxy:
+ name = "nt"
+
+ def __getattr__(self, name):
+ return getattr(os, name)
+
+ monkeypatch.setattr(api, "os", WindowsOsProxy())
+ monkeypatch.setattr(api, "build_upgrade_plan", lambda **_kwargs: plan)
+ monkeypatch.setattr(api, "get_version_info", lambda: {"latest": "99"})
+ monkeypatch.setattr(api, "get_running_vibe_path", lambda: str(launcher))
+ monkeypatch.setattr(api, "_runtime_process_was_running", lambda: False)
+ monkeypatch.setattr(api, "activation_block_reason", lambda _activation: None)
+ monkeypatch.setattr(api, "launcher_is_current_process", lambda _launcher: True)
+ monkeypatch.setattr(api, "verify_upgrade_candidate", lambda _activation: upgrade.IntegrityResult(True))
+ monkeypatch.setattr(
+ api,
+ "defer_upgrade_activation",
+ lambda *_args, **_kwargs: SimpleNamespace(activation_log_path=root / "upgrade.log"),
+ )
+ if failure == "metadata":
+ monkeypatch.setattr(
+ api,
+ "get_deferred_activation_log_path",
+ lambda _process: (_ for _ in ()).throw(RuntimeError("log metadata failed")),
+ )
+ else:
+ monkeypatch.setattr(
+ api,
+ "format_deferred_activation_log",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("log formatting failed")),
+ )
+ monkeypatch.setattr(
+ api,
+ "execute_upgrade_plan",
+ lambda *_args, **_kwargs: subprocess.CompletedProcess(plan.command, 0, "done", ""),
+ )
+
+ result = api.do_upgrade(auto_restart=False)
+
+ assert result["ok"] is True
+ assert result["message"] == "Upgrade successful. Activation will complete after this process exits."
+ assert "log metadata failed" in result["output"] or "log formatting failed" in result["output"]
+ assert result["activation_notice"] is None
+ assert exported.exists()
+ assert (root / "deferred").exists()
+
+
@pytest.mark.parametrize("state,owner,old_status,marker_job,deferred", [
("failed", "live", False, "active", False),
("error", "dead", False, "active", False),
diff --git a/tests/test_install_script.py b/tests/test_install_script.py
index dc11fe6b8..317af05b3 100644
--- a/tests/test_install_script.py
+++ b/tests/test_install_script.py
@@ -59,12 +59,47 @@ def _run(command: str, *, cwd: Path, env: dict[str, str], timeout: int = 30) ->
def _write_fake_uv(path: Path, uv_log: Path) -> None:
- activation_driver = (
- f"import sys; sys.path.insert(0, {str(REPO_ROOT)!r}); "
- "from vibe import cli, upgrade, install_generations; "
- "upgrade.verify_upgrade_candidate = lambda activation: upgrade.IntegrityResult(True, 1); "
- "sys.exit(cli._dispatch_installer_activation(sys.argv[1:]))"
+ activation_driver_source = textwrap.dedent(
+ f"""
+ import io
+ import os
+ import sys
+ from pathlib import Path
+
+ sys.path.insert(0, {str(REPO_ROOT)!r})
+ from vibe import cli, upgrade
+
+ upgrade.verify_upgrade_candidate = lambda activation: upgrade.IntegrityResult(True, 1)
+ if os.environ.get("VIBE_TEST_ACTIVATION_PEER_FAILURE") == "1":
+ _activate = cli.activate_installer_candidate
+
+ def _activate_with_peer_failure(activation):
+ outcome = _activate(activation)
+ failure = upgrade.LauncherActivationFailure(
+ Path(os.environ["VIBE_TEST_PEER_PATH"]),
+ "permission denied",
+ "permission_denied",
+ )
+ return upgrade.ActivationOutcome(outcome.activated_launcher, (failure,))
+
+ cli.activate_installer_candidate = _activate_with_peer_failure
+ cli._configured_cli_language = lambda: "zh"
+ if os.environ.get("VIBE_TEST_CP1252_DIAGNOSTIC") == "1":
+ sys.stdout = io.TextIOWrapper(
+ os.fdopen(os.dup(1), "wb"),
+ encoding="cp1252",
+ write_through=True,
+ )
+ if os.environ.get("VIBE_TEST_CLOSE_DIAGNOSTIC_PIPE") == "1":
+ if "--candidate" in sys.argv:
+ _read_fd, _write_fd = os.pipe()
+ os.close(_read_fd)
+ os.dup2(_write_fd, 1)
+ os.close(_write_fd)
+ sys.exit(cli._dispatch_installer_activation(sys.argv[1:]))
+ """
)
+ activation_driver = f"exec({activation_driver_source!r})"
receipt_driver = (
"import json, sys; from pathlib import Path; "
"environment = Path(sys.argv[1]); environment.mkdir(parents=True, exist_ok=True); "
@@ -125,6 +160,9 @@ def _write_fake_uv(path: Path, uv_log: Path) -> None:
#!/usr/bin/env bash
set -euo pipefail
if [ "${{VIBE_TEST_SHARED_ACTIVATION:-}}" = "1" ] && [ "${{1:-}}" = "__activate-install" ]; then
+ if [ -n "${{VIBE_TEST_SHARED_ACTIVATION_LOG:-}}" ]; then
+ printf '%s' "$*" > "$VIBE_TEST_SHARED_ACTIVATION_LOG"
+ fi
exec "{sys.executable}" -c {shlex.quote(activation_driver)} "${{@:2}}"
fi
if [ "${{VIBE_TEST_REQUIRE_CANONICAL_HOME:-}}" = "1" ] && \
@@ -593,6 +631,43 @@ def test_install_script_uses_the_current_owner_for_a_legacy_candidate(tmp_path):
assert (path_dir / "vibe").resolve() != first_owner
[email protected]("sink", ["cp1252", "closed-pipe"])
+def test_install_script_preserves_committed_generation_when_advisory_sink_fails(tmp_path, sink):
+ home_dir = tmp_path / "home"
+ home_dir.mkdir()
+ path_dir = tmp_path / "path-bin"
+ path_dir.mkdir()
+ uv_log = tmp_path / "uv-tool-bin-dir.txt"
+ shared_activation_log = tmp_path / "shared-activation.txt"
+ _write_fake_uv(path_dir / "uv", uv_log)
+
+ env = os.environ.copy()
+ env["HOME"] = str(home_dir)
+ env["PATH"] = os.pathsep.join([str(path_dir), "/usr/bin", "/bin"])
+ env["VIBE_TEST_SHARED_ACTIVATION"] = "1"
+ env["VIBE_TEST_SHARED_ACTIVATION_LOG"] = str(shared_activation_log)
+ env["VIBE_TEST_ACTIVATION_PEER_FAILURE"] = "1"
+ env["VIBE_TEST_PEER_PATH"] = str(tmp_path / "peer 空格" / "vibe")
+ if sink == "cp1252":
+ env["VIBE_TEST_CP1252_DIAGNOSTIC"] = "1"
+ else:
+ env["VIBE_TEST_CLOSE_DIAGNOSTIC_PIPE"] = "1"
+
+ install_result = _install(env)
+ launcher = path_dir / "vibe"
+ version_result = _vibe_version(env)
+
+ assert install_result.returncode == 0, install_result.stdout + install_result.stderr
+ assert launcher.is_symlink()
+ assert launcher.resolve().is_file()
+ assert version_result.returncode == 0, version_result.stdout + version_result.stderr
+ assert shared_activation_log.read_text(encoding="utf-8").startswith("__activate-install ")
+ assert "avibe-os 9.9.9" in version_result.stdout
+ if sink == "cp1252":
+ assert "doctor repair stable-launchers" in install_result.stdout
+ assert r"\u" in install_result.stdout
+
+
def test_install_script_recovers_an_existing_3_0_13_generation(tmp_path):
home_dir = tmp_path / "home"
home_dir.mkdir()
diff --git a/tests/test_upgrade_flow.py b/tests/test_upgrade_flow.py
index a3a860335..6ec001d7b 100644
--- a/tests/test_upgrade_flow.py
+++ b/tests/test_upgrade_flow.py
@@ -1,7 +1,9 @@
from __future__ import annotations
from contextlib import nullcontext
+import io
import os
+import shlex
import stat
import subprocess
import sys
@@ -578,7 +580,11 @@ def test_deferred_activation_dispatch_activates_then_schedules_restart(monkeypat
monkeypatch.setattr(cli.runtime, "pid_alive", lambda _pid: False)
monkeypatch.setattr(cli, "atomic_upgrade_lock", lambda: nullcontext())
monkeypatch.setattr(cli, "activation_block_reason", lambda _activation: None)
- monkeypatch.setattr(cli, "activate_upgrade_candidate", lambda _activation: calls.append("activate"))
+ monkeypatch.setattr(
+ cli,
+ "activate_upgrade_candidate",
+ lambda _activation: calls.append("activate") or vibe_upgrade.ActivationOutcome(launcher),
+ )
monkeypatch.setattr(cli, "schedule_restart", lambda **_kwargs: calls.append("restart"))
result = cli._dispatch_deferred_upgrade_activation(
@@ -612,7 +618,11 @@ def test_deferred_activation_seeds_restart_before_releasing_install_lock(monkeyp
monkeypatch.setattr(cli.runtime, "pid_alive", lambda _pid: False)
monkeypatch.setattr(cli, "atomic_upgrade_lock", Lock)
monkeypatch.setattr(cli, "activation_block_reason", lambda _activation: None)
- monkeypatch.setattr(cli, "activate_upgrade_candidate", lambda _activation: events.append("activate"))
+ monkeypatch.setattr(
+ cli,
+ "activate_upgrade_candidate",
+ lambda _activation: events.append("activate") or vibe_upgrade.ActivationOutcome(tmp_path / "vibe.exe"),
+ )
monkeypatch.setattr(cli, "schedule_restart", lambda **_kwargs: events.append("restart"))
result = cli._dispatch_deferred_upgrade_activation(
@@ -631,16 +641,76 @@ def test_deferred_activation_seeds_restart_before_releasing_install_lock(monkeyp
assert events == ["lock-enter", "activate", "restart", "lock-exit"]
-def test_deferred_offline_activation_prepares_show_runtime(monkeypatch, tmp_path):
+def test_deferred_activation_notice_failure_does_not_skip_restart(monkeypatch, tmp_path):
from vibe import cli
- calls: list[str] = []
+ events: list[str] = []
launcher = tmp_path / "vibe.exe"
+
monkeypatch.setattr(cli.runtime, "pid_alive", lambda _pid: False)
monkeypatch.setattr(cli, "atomic_upgrade_lock", lambda: nullcontext())
monkeypatch.setattr(cli, "activation_block_reason", lambda _activation: None)
- monkeypatch.setattr(cli, "activate_upgrade_candidate", lambda _activation: calls.append("activate"))
- monkeypatch.setattr(cli, "_prepare_show_runtime_after_install", lambda path: calls.append(f"prepare:{path}"))
+ monkeypatch.setattr(
+ cli,
+ "activate_upgrade_candidate",
+ lambda _activation: events.append("activate") or vibe_upgrade.ActivationOutcome(launcher),
+ )
+ monkeypatch.setattr(cli, "schedule_restart", lambda **_kwargs: events.append("restart"))
+ monkeypatch.setattr(
+ cli,
+ "format_activation_failures",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("notice failed")),
+ )
+
+ result = cli._dispatch_deferred_upgrade_activation(
+ [
+ "--parent-pid",
+ "123",
+ "--launcher",
+ str(launcher),
+ "--candidate",
+ str(tmp_path / "candidate.exe"),
+ "--restart",
+ ]
+ )
+
+ assert result == 0
+ assert events == ["activate", "restart"]
+
+
+def test_deferred_offline_activation_prepares_show_runtime_after_releasing_lock(
+ monkeypatch, tmp_path,
+):
+ from vibe import cli
+
+ events: list[str] = []
+ launcher = tmp_path / "vibe.exe"
+
+ class Lock:
+ def __enter__(self):
+ events.append("lock-enter")
+
+ def __exit__(self, *_args):
+ events.append("lock-exit")
+
+ monkeypatch.setattr(cli.runtime, "pid_alive", lambda _pid: False)
+ monkeypatch.setattr(cli, "atomic_upgrade_lock", Lock)
+ monkeypatch.setattr(cli, "activation_block_reason", lambda _activation: None)
+ monkeypatch.setattr(
+ cli,
+ "activate_upgrade_candidate",
+ lambda _activation: events.append("activate") or vibe_upgrade.ActivationOutcome(launcher),
+ )
+ monkeypatch.setattr(
+ cli,
+ "_prepare_show_runtime_after_install",
+ lambda path: events.append(f"prepare:{path}"),
+ )
+ monkeypatch.setattr(
+ cli,
+ "format_activation_failures",
+ lambda *_args, **_kwargs: events.append("notice") or None,
+ )
result = cli._dispatch_deferred_upgrade_activation(
[
@@ -655,7 +725,46 @@ def test_deferred_offline_activation_prepares_show_runtime(monkeypatch, tmp_path
)
assert result == 0
- assert calls == ["activate", f"prepare:{launcher}"]
+ assert events == ["lock-enter", "activate", "lock-exit", f"prepare:{launcher}", "notice"]
+
+
+def test_deferred_offline_activation_prepare_failure_is_truthful(
+ monkeypatch, tmp_path, capsys,
+):
+ from vibe import cli
+
+ events: list[str] = []
+ launcher = tmp_path / "vibe.exe"
+ monkeypatch.setattr(cli.runtime, "pid_alive", lambda _pid: False)
+ monkeypatch.setattr(cli, "atomic_upgrade_lock", lambda: nullcontext())
+ monkeypatch.setattr(cli, "activation_block_reason", lambda _activation: None)
+ monkeypatch.setattr(
+ cli,
+ "activate_upgrade_candidate",
+ lambda _activation: events.append("activate") or vibe_upgrade.ActivationOutcome(launcher),
+ )
+ monkeypatch.setattr(
+ cli,
+ "_prepare_show_runtime_after_install",
+ lambda _path: (_ for _ in ()).throw(RuntimeError("runtime unavailable")),
+ )
+ monkeypatch.setattr(cli, "_emit_activation_notice", lambda _outcome: events.append("notice"))
+
+ result = cli._dispatch_deferred_upgrade_activation(
+ [
+ "--parent-pid",
+ "123",
+ "--launcher",
+ str(launcher),
+ "--candidate",
+ str(tmp_path / "candidate.exe"),
+ "--prepare-show-runtime",
+ ]
+ )
+
+ assert result == 1
+ assert events == ["activate"]
+ assert "Show Runtime preparation failed: runtime unavailable" in capsys.readouterr().err
def test_deferred_upgrade_activation_uses_candidate_python(monkeypatch, tmp_path):
@@ -701,6 +810,7 @@ def test_deferred_upgrade_activation_uses_candidate_python(monkeypatch, tmp_path
assert "--restart" in calls["command"]
assert "--prepare-show-runtime" in calls["command"]
assert calls["kwargs"]["env"] == {"PATH": "clean"}
+ assert process.activation_log_path.parent == tmp_path / "logs"
assert (candidate.parent.parent / ".avibe-installing").read_text() == "456"
@@ -904,6 +1014,247 @@ def test_do_upgrade_keeps_active_launcher_when_staged_install_fails(monkeypatch,
assert launcher.resolve() == old.resolve()
+ ("language", "expected"),
+ [("en", "Upgrade activated the new version"), ("zh", "升级已激活新版本")],
+)
+def test_cmd_upgrade_reports_peer_activation_failures(monkeypatch, tmp_path, capsys, language, expected):
+ launcher = tmp_path / "activated home 空格" / "vibe"
+ peer = tmp_path / "peer home 空格" / "稳定-vibe"
+ outcome = vibe_upgrade.ActivationOutcome(
+ activated_launcher=launcher,
+ peer_failures=(
+ vibe_upgrade.LauncherActivationFailure(peer, "permission denied", "permission_denied"),
+ ),
+ )
+ plan = UpgradePlan(
+ command=["uv", "tool", "install", "avibe-os", "--upgrade"],
+ env={},
+ method="uv",
+ activation=AtomicActivation(launcher, tmp_path / "candidate" / "vibe"),
+ )
+ monkeypatch.setattr(cli, "get_latest_version", lambda: {
+ "error": None, "has_update": True, "latest": "2.2.0",
+ })
+ monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: str(launcher))
+ monkeypatch.setattr(cli, "build_upgrade_plan", lambda **_kwargs: plan)
+ monkeypatch.setattr(cli, "_runtime_process_was_running", lambda: False)
+ monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)
+ monkeypatch.setattr(cli, "activate_upgrade_candidate", lambda _activation: outcome)
+ monkeypatch.setattr(
+ cli,
+ "execute_upgrade_plan",
+ lambda *_args, **_kwargs: subprocess.CompletedProcess(plan.command, 0, stdout="done", stderr=""),
+ )
+ monkeypatch.setattr(cli, "_prepare_show_runtime_after_install", lambda *_args: None)
+ monkeypatch.setattr(
+ cli.subprocess,
+ "run",
+ lambda cmd, **kwargs: subprocess.CompletedProcess(cmd, 0, stdout="done", stderr=""),
+ )
+
+ assert cli.cmd_upgrade() == 0
+ output = capsys.readouterr().out
+ assert expected in output
+ assert str(peer) in output
+ assert "permission denied" in output
+ assert "doctor repair stable-launchers" in output
+ assert str(launcher) in output
+
+
+def test_cmd_upgrade_prepares_show_runtime_before_activation_notice(monkeypatch, tmp_path):
+ launcher = tmp_path / "activated-vibe"
+ outcome = vibe_upgrade.ActivationOutcome(activated_launcher=launcher)
+ plan = UpgradePlan(
+ command=["uv", "tool", "install", "avibe-os", "--upgrade"],
+ env={},
+ method="uv",
+ activation=AtomicActivation(launcher, tmp_path / "candidate" / "vibe"),
+ )
+ events: list[str] = []
+ monkeypatch.setattr(cli, "get_latest_version", lambda: {
+ "error": None, "has_update": True, "latest": "2.2.0",
+ })
+ monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: str(launcher))
+ monkeypatch.setattr(cli, "build_upgrade_plan", lambda **_kwargs: plan)
+ monkeypatch.setattr(cli, "_runtime_process_was_running", lambda: False)
+ monkeypatch.setattr(cli, "activate_upgrade_candidate", lambda _activation: events.append("activate") or outcome)
+ monkeypatch.setattr(
+ cli,
+ "execute_upgrade_plan",
+ lambda *_args, **_kwargs: subprocess.CompletedProcess(plan.command, 0, stdout="done", stderr=""),
+ )
+ monkeypatch.setattr(cli, "_prepare_show_runtime_after_install", lambda _path: events.append("prepare"))
+ monkeypatch.setattr(
+ cli,
+ "format_activation_failures",
+ lambda *_args, **_kwargs: events.append("notice") or None,
+ )
+
+ assert cli.cmd_upgrade() == 0
+ assert events == ["activate", "prepare", "notice"]
+
+
+def test_do_upgrade_includes_peer_activation_failures_in_output(monkeypatch, tmp_path):
+ launcher = tmp_path / "activated-vibe"
+ peer = tmp_path / "peer-vibe"
+ outcome = vibe_upgrade.ActivationOutcome(
+ activated_launcher=launcher,
+ peer_failures=(vibe_upgrade.LauncherActivationFailure(peer, "transient I/O failure"),),
+ )
+ plan = UpgradePlan(
+ command=["uv", "tool", "install", "avibe-os", "--upgrade"],
+ env={},
+ method="uv",
+ activation=AtomicActivation(launcher, tmp_path / "candidate" / "vibe"),
+ )
+ monkeypatch.setattr(api, "get_version_info", lambda: {"latest": "2.2.0"})
+ monkeypatch.setattr(api, "get_running_vibe_path", lambda: str(launcher))
+ monkeypatch.setattr(api, "build_upgrade_plan", lambda **_kwargs: plan)
+ monkeypatch.setattr(api, "_runtime_process_was_running", lambda: False)
+ monkeypatch.setattr(api, "_configured_backend_language", lambda: "zh")
+ monkeypatch.setattr(api, "activate_upgrade_candidate", lambda _activation: outcome)
+ monkeypatch.setattr(
+ api,
+ "execute_upgrade_plan",
+ lambda *_args, **_kwargs: subprocess.CompletedProcess(plan.command, 0, stdout="done", stderr=""),
+ )
+ monkeypatch.setattr(api, "_prepare_show_runtime_after_upgrade", lambda *_args: None)
+ monkeypatch.setattr(
+ api.subprocess,
+ "run",
+ lambda cmd, **kwargs: subprocess.CompletedProcess(cmd, 0, stdout="done", stderr=""),
+ )
+
+ result = api.do_upgrade(auto_restart=False)
+
+ assert result["ok"] is True
+ assert "升级已激活新版本" in result["output"]
+ assert str(peer) in result["output"]
+ assert "transient I/O failure" in result["output"]
+ assert "doctor repair stable-launchers" in result["output"]
+ assert str(launcher) in result["output"]
+ assert "请先处理所报告的原因" in result["output"]
+ assert "其余仍受管理的稳定启动器" in result["output"]
+ assert result["activation_notice"] == result["output"].split("\n\n", 1)[1]
+
+
+def test_activation_repair_command_quotes_full_launcher_path(tmp_path):
+ launcher = tmp_path / "activated home 空格" / "vibe"
+
+ command = vibe_upgrade.activation_repair_command(launcher)
+
+ assert command == shlex.join([
+ str(launcher.absolute()),
+ "doctor",
+ "repair",
+ "stable-launchers",
+ ])
+
+
+def test_activation_repair_command_is_power_shell_invocable(monkeypatch, tmp_path):
+ launcher = tmp_path / "用户's home 空格" / "vibe.exe"
+
+ class WindowsOsProxy:
+ name = "nt"
+ path = os.path
+
+ monkeypatch.setattr(vibe_upgrade, "os", WindowsOsProxy())
+
+ command = vibe_upgrade.activation_repair_command(launcher)
+
+ escaped = str(launcher.absolute()).replace("'", "''")
+ assert command == f"& '{escaped}' doctor repair stable-launchers"
+
+
+ "reason_code",
+ ["permission_denied", "launcher_changed_after_discovery", "move_failed"],
+)
[email protected]("language", ["en", "zh"])
+def test_windows_activation_notices_label_powershell_for_each_failure(
+ monkeypatch, tmp_path, reason_code, language,
+):
+ launcher = tmp_path / "用户's activated home 空格" / "vibe.exe"
+ peer = tmp_path / "peer home 空格" / "稳定-vibe.exe"
+
+ class WindowsOsProxy:
+ name = "nt"
+ path = os.path
+
+ monkeypatch.setattr(vibe_upgrade, "os", WindowsOsProxy())
+ outcome = vibe_upgrade.ActivationOutcome(
+ activated_launcher=launcher,
+ peer_failures=(
+ vibe_upgrade.LauncherActivationFailure(
+ peer,
+ "the launcher changed after discovery"
+ if reason_code == "launcher_changed_after_discovery"
+ else "move failed",
+ reason_code,
+ ),
+ ),
+ )
+
+ notice = vibe_upgrade.format_activation_failures(outcome, language)
+
+ assert notice is not None
+ assert "PowerShell" in notice
+ if language == "en":
+ assert "in PowerShell, run" in notice
+ assert "In PowerShell, run" not in notice
+ assert str(launcher.absolute()).replace("'", "''") in notice
+ assert "doctor repair stable-launchers" in notice
+
+
+def test_do_upgrade_surfaces_deferred_activation_log(monkeypatch, tmp_path):
+ launcher = tmp_path / "bin" / "vibe.exe"
+ candidate = tmp_path / "generation" / "bin" / "vibe.exe"
+ log_path = tmp_path / "logs" / "upgrade-activation-test.log"
+ plan = UpgradePlan(
+ command=["uv", "tool", "install", "avibe-os", "--upgrade"],
+ env=None,
+ method="uv",
+ activation=AtomicActivation(launcher, candidate),
+ )
+
+ class WindowsOsProxy:
+ name = "nt"
+
+ def __getattr__(self, name):
+ return getattr(os, name)
+
+ monkeypatch.setattr(api, "os", WindowsOsProxy())
+ monkeypatch.setattr(api, "build_upgrade_plan", lambda **_kwargs: plan)
+ monkeypatch.setattr(api, "get_version_info", lambda: {"latest": "2.2.0"})
+ monkeypatch.setattr(api, "get_running_vibe_path", lambda: str(launcher))
+ monkeypatch.setattr(api, "_runtime_process_was_running", lambda: False)
+ monkeypatch.setattr(api, "_configured_backend_language", lambda: "en")
+ monkeypatch.setattr(api, "activation_block_reason", lambda _activation: None)
+ monkeypatch.setattr(api, "launcher_is_current_process", lambda _launcher: True)
+ monkeypatch.setattr(api, "verify_upgrade_candidate", lambda _activation: vibe_upgrade.IntegrityResult(True))
+ monkeypatch.setattr(api, "defer_upgrade_activation", lambda *_args, **_kwargs: SimpleNamespace(
+ activation_log_path=log_path,
+ ))
+ monkeypatch.setattr(
+ api,
+ "execute_upgrade_plan",
+ lambda *_args, **_kwargs: subprocess.CompletedProcess(plan.command, 0, stdout="done", stderr=""),
+ )
+ monkeypatch.setattr(
+ api.subprocess,
+ "run",
+ lambda cmd, **kwargs: subprocess.CompletedProcess(cmd, 0, stdout="done", stderr=""),
+ )
+
+ result = api.do_upgrade(auto_restart=False)
+
+ assert result["ok"] is True
+ assert str(log_path) in result["output"]
+ assert "deferred activation helper" in result["output"]
+ assert result["activation_notice"] == "The deferred activation helper will record its result in " + str(log_path) + "."
+
+
def test_build_upgrade_plan_uses_env_package_spec(monkeypatch):
monkeypatch.setenv("VIBE_UPGRADE_PACKAGE_SPEC", "/tmp/vibe_remote-9999.0.0-py3-none-any.whl")
monkeypatch.setattr("vibe.upgrade.os.path.exists", lambda path: True)
@@ -1044,6 +1395,7 @@ def test_do_upgrade_rejects_desktop_managed_runtime(monkeypatch):
"ok": False,
"message": "This Runtime is managed by the Avibe desktop app.",
"output": None,
+ "activation_notice": None,
"restarting": False,
"code": "desktop_managed_runtime",
}
@@ -1345,6 +1697,8 @@ def test_cmd_upgrade_reports_restart_scheduling_failure_as_partial_success(monke
raise RuntimeError("bad launcher")
monkeypatch.setattr(cli, "schedule_restart", fail_restart)
+ prepared: list[str] = []
+ monkeypatch.setattr(cli, "_prepare_show_runtime_after_install", lambda path: prepared.append(path))
monkeypatch.setattr(
cli.subprocess,
"run",
@@ -1357,6 +1711,70 @@ def test_cmd_upgrade_reports_restart_scheduling_failure_as_partial_success(monke
assert "Restart error: bad launcher" in output
assert "Run `vibe restart` to use the new version." in output
assert "Upgrade failed" not in output
+ assert prepared == []
+
+
[email protected]("sink", ["cp1252", "closed-pipe"])
+def test_cmd_upgrade_preserves_restart_failure_when_advisory_output_fails(
+ monkeypatch, sink,
+):
+ plan = UpgradePlan(
+ command=["/usr/local/bin/uv", "tool", "install", "avibe-os", "--upgrade"],
+ env=None,
+ method="uv",
+ )
+
+ monkeypatch.setattr(cli, "get_latest_version", lambda: {"error": None, "has_update": True, "latest": "2.2.0"})
+ monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: "/custom/bin/vibe")
+ monkeypatch.setattr(cli, "build_upgrade_plan", lambda **kwargs: plan)
+ monkeypatch.setattr(cli, "_runtime_process_was_running", lambda: True)
+ monkeypatch.setattr(
+ cli,
+ "execute_upgrade_plan",
+ lambda _plan, **kwargs: subprocess.CompletedProcess(plan.command, 0, stdout="done", stderr=""),
+ )
+ monkeypatch.setattr(
+ cli,
+ "schedule_restart",
+ lambda **kwargs: (_ for _ in ()).throw(
+ PermissionError("权限不足") if sink == "cp1252" else RuntimeError("closed pipe")
+ ),
+ )
+
+ if sink == "cp1252":
+ class Cp1252Stream(io.StringIO):
+ @property
+ def encoding(self):
+ return "cp1252"
+
+ def write(self, text):
+ text.encode(self.encoding)
+ return super().write(text)
+
+ stream = Cp1252Stream()
+ else:
+ class ClosedReportStream:
+ encoding = "utf-8"
+
+ def __init__(self):
+ self.parts: list[str] = []
+
+ def write(self, text):
+ if "Restart error:" in text:
+ raise BrokenPipeError("closed pipe")
+ self.parts.append(text)
+ return len(text)
+
+ def flush(self):
+ return None
+
+ stream = ClosedReportStream()
+
+ monkeypatch.setattr(cli.sys, "stdout", stream)
+
+ assert cli.cmd_upgrade() == 2
+ if sink == "cp1252":
+ assert r"\u6743\u9650" in stream.getvalue()
def test_cmd_upgrade_keeps_runtime_stopped_when_it_was_not_running(monkeypatch):
diff --git a/ui/src/components/VersionBadge.test.tsx b/ui/src/components/VersionBadge.test.tsx
index 30fc1406d..5751cb550 100644
--- a/ui/src/components/VersionBadge.test.tsx
+++ b/ui/src/components/VersionBadge.test.tsx
@@ -8,6 +8,7 @@ import { VersionBadge } from './VersionBadge';
const api = vi.hoisted(() => ({
getVersion: vi.fn(async () => ({ current: '9.9.9', latest: '10.0.0', has_update: true, managed_by: 'desktop' })),
getConfig: vi.fn(async () => ({ update: { auto_update: true } })),
+ doUpgrade: vi.fn(async () => ({ ok: true, message: 'Upgrade successful', output: null, restarting: false })),
}));
vi.mock('../context/ApiContext', () => ({ useApi: () => api }));
vi.mock('../lib/useIsDesktop', () => ({ useIsDesktop: () => true }));
@@ -54,4 +55,78 @@ describe('desktop version ownership', () => {
expect(api.getVersion).toHaveBeenCalledOnce();
expect(entry.querySelector('.animate-pulse')).toBeNull();
});
+
+ it('shows a successful upgrade warning returned in the output', async () => {
+ api.getVersion.mockResolvedValueOnce({ current: '9.9.9', latest: '10.0.0', has_update: true });
+ api.doUpgrade.mockResolvedValueOnce({
+ ok: true,
+ message: 'Upgrade successful',
+ output: 'raw installer transcript',
+ activation_notice: 'Stable launcher repair is still required.',
+ restarting: false,
+ });
+ render(<I18nextProvider i18n={i18n}><VersionBadge /></I18nextProvider>);
+
+ fireEvent.click(await screen.findByTitle('v9.9.9'));
+ fireEvent.click(await screen.findByRole('button', { name: i18n.t('dashboard.upgradeNow') }));
+
+ expect(await screen.findByText('Stable launcher repair is still required.')).toBeTruthy();
+ expect(screen.queryByText('raw installer transcript')).toBeNull();
+ expect(api.doUpgrade).toHaveBeenCalledOnce();
+ });
+
+ it('shows the deferred activation log notice without rendering raw output', async () => {
+ api.getVersion.mockResolvedValueOnce({ current: '9.9.9', latest: '10.0.0', has_update: true });
+ api.doUpgrade.mockResolvedValueOnce({
+ ok: true,
+ message: 'Upgrade successful. Activation will complete after this process exits.',
+ output: 'raw deferred helper transcript',
+ activation_notice: 'The deferred activation helper will record its result in /tmp/upgrade.log.',
+ restarting: false,
+ });
+ render(<I18nextProvider i18n={i18n}><VersionBadge /></I18nextProvider>);
+
+ fireEvent.click(await screen.findByTitle('v9.9.9'));
+ fireEvent.click(await screen.findByRole('button', { name: i18n.t('dashboard.upgradeNow') }));
+
+ expect(await screen.findByText(/deferred activation helper/)).toBeTruthy();
+ expect(screen.queryByText('raw deferred helper transcript')).toBeNull();
+ });
+
+ it('keeps a clean successful banner when only raw output is returned', async () => {
+ api.getVersion.mockResolvedValueOnce({ current: '9.9.9', latest: '10.0.0', has_update: true });
+ api.doUpgrade.mockResolvedValueOnce({
+ ok: true,
+ message: 'Upgrade successful',
+ output: 'installer stdout\nShow Runtime prepared.',
+ activation_notice: null,
+ restarting: false,
+ });
+ render(<I18nextProvider i18n={i18n}><VersionBadge /></I18nextProvider>);
+
+ fireEvent.click(await screen.findByTitle('v9.9.9'));
+ fireEvent.click(await screen.findByRole('button', { name: i18n.t('dashboard.upgradeNow') }));
+
+ expect(await screen.findByText(i18n.t('dashboard.upgradeSuccess'))).toBeTruthy();
+ expect(screen.queryByText(/installer stdout/)).toBeNull();
+ expect(screen.queryByText(/Show Runtime prepared/)).toBeNull();
+ });
+
+ it('keeps the localized failure banner free of raw output', async () => {
+ api.getVersion.mockResolvedValueOnce({ current: '9.9.9', latest: '10.0.0', has_update: true });
+ api.doUpgrade.mockResolvedValueOnce({
+ ok: false,
+ message: '升级失败',
+ output: 'raw package-manager transcript',
+ activation_notice: null,
+ restarting: false,
+ });
+ render(<I18nextProvider i18n={i18n}><VersionBadge /></I18nextProvider>);
+
+ fireEvent.click(await screen.findByTitle('v9.9.9'));
+ fireEvent.click(await screen.findByRole('button', { name: i18n.t('dashboard.upgradeNow') }));
+
+ expect(await screen.findByText(i18n.t('dashboard.upgradeFailed'))).toBeTruthy();
+ expect(screen.queryByText('raw package-manager transcript')).toBeNull();
+ });
});
diff --git a/ui/src/components/VersionBadge.tsx b/ui/src/components/VersionBadge.tsx
index a4c6a3fcb..945319855 100644
--- a/ui/src/components/VersionBadge.tsx
+++ b/ui/src/components/VersionBadge.tsx
@@ -132,7 +132,7 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
}
}
} catch (e) {
- setUpgradeResult({ ok: false, message: String(e), output: null, restarting: false });
+ setUpgradeResult({ ok: false, message: String(e), output: null, activation_notice: null, restarting: false });
} finally {
setUpgrading(false);
}
@@ -299,16 +299,21 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
{upgradeResult && (
<div
className={clsx(
- 'flex items-center gap-2 rounded-md border px-3 py-2 text-sm',
+ 'flex items-start gap-2 rounded-md border px-3 py-2 text-sm',
upgradeResult.ok
? 'border-mint/25 bg-mint/10 text-mint-ink'
: 'border-destructive/30 bg-destructive/10 text-destructive-ink'
)}
>
{upgradeResult.ok ? <Check size={16} className="shrink-0" /> : <AlertCircle size={16} className="shrink-0" />}
- <span>
+ <div className="min-w-0 space-y-1">
{upgradeResult.ok ? t('dashboard.upgradeSuccess') : t('dashboard.upgradeFailed')}
- </span>
+ {upgradeResult.ok && upgradeResult.activation_notice && (
+ <div className="whitespace-pre-wrap break-words text-xs">
+ {upgradeResult.activation_notice}
+ </div>
+ )}
+ </div>
</div>
)}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 9e3d553cd..7aea401a0 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1889,6 +1889,7 @@ export type UpgradeResult = {
ok: boolean;
message: string;
output: string | null;
+ activation_notice?: string | null;
restarting: boolean;
code?: string;
};
diff --git a/vibe/api.py b/vibe/api.py
index 0251db2c2..ed5163511 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -89,9 +89,12 @@ from vibe.upgrade import (
defer_upgrade_activation,
discard_atomic_uv_install_generation,
execute_upgrade_plan,
+ format_deferred_activation_log,
get_latest_version_info,
get_running_vibe_path,
get_safe_cwd,
+ format_activation_failures,
+ get_deferred_activation_log_path,
is_desktop_managed_runtime,
launcher_is_current_process,
restart_is_pending,
@@ -6159,13 +6162,20 @@ def do_upgrade(auto_restart: bool = True) -> dict:
auto_restart: If True, restart vibe after successful upgrade
Returns:
- {"ok": bool, "message": str, "output": str | None, "restarting": bool}
+ {
+ "ok": bool,
+ "message": str,
+ "output": str | None,
+ "activation_notice": str | None,
+ "restarting": bool,
+ }
"""
if is_desktop_managed_runtime():
return {
"ok": False,
"message": backend_t("desktopRuntime.apiUpgrade", V2Config.load().language),
"output": None,
+ "activation_notice": None,
"restarting": False,
"code": "desktop_managed_runtime",
}
@@ -6177,12 +6187,19 @@ def do_upgrade(auto_restart: bool = True) -> dict:
target_version=get_version_info().get("latest"),
)
except ValueError as exc:
- return {"ok": False, "message": "Upgrade failed.", "output": str(exc), "restarting": False}
+ return {
+ "ok": False,
+ "message": "Upgrade failed.",
+ "output": str(exc),
+ "activation_notice": None,
+ "restarting": False,
+ }
if plan.preflight_error:
return {
"ok": False,
"message": "Upgrade cannot be activated safely",
"output": plan.preflight_error,
+ "activation_notice": None,
"restarting": False,
}
runtime_was_running = _runtime_process_was_running()
@@ -6195,7 +6212,13 @@ def do_upgrade(auto_restart: bool = True) -> dict:
restart_failed = False
runtime_output = None
deferred_activation = False
+ deferred_activation_log = None
+ deferred_activation_log_error = None
restart_python = None
+ activation_outcome = None
+ activation_notice = None
+ activation_committed = False
+ activation_postcommit_error = None
try:
with atomic_upgrade_lock():
@@ -6204,6 +6227,7 @@ def do_upgrade(auto_restart: bool = True) -> dict:
"ok": False,
"message": "Upgrade already has a restart in progress",
"output": "Wait for the pending restart to finish before starting another upgrade.",
+ "activation_notice": None,
"restarting": False,
}
if plan.activation is not None and activation_block_reason(plan.activation) == "superseded":
@@ -6211,6 +6235,7 @@ def do_upgrade(auto_restart: bool = True) -> dict:
"ok": False,
"message": "Upgrade was superseded by another activation",
"output": "The active Avibe generation changed while waiting for the upgrade lock; retry the upgrade.",
+ "activation_notice": None,
"restarting": False,
}
result = execute_upgrade_plan(
@@ -6232,24 +6257,38 @@ def do_upgrade(auto_restart: bool = True) -> dict:
candidate_result = verify_upgrade_candidate(plan.activation)
if not candidate_result.ok:
raise RuntimeError(candidate_result.detail)
- defer_upgrade_activation(
+ deferred_process = defer_upgrade_activation(
plan.activation,
parent_pid=os.getpid(),
restart_required=auto_restart and runtime_was_running,
prepare_show_runtime=not should_skip_show_runtime_prepare(),
)
+ activation_committed = True
deferred_activation = True
+ try:
+ deferred_activation_log = get_deferred_activation_log_path(deferred_process)
+ except Exception as exc: # noqa: BLE001
+ deferred_activation_log_error = str(exc)
else:
restart_python = _candidate_python(plan.activation.candidate_launcher)
- activate_upgrade_candidate(plan.activation)
+ activation_outcome = activate_upgrade_candidate(plan.activation)
+ activation_committed = True
except Exception as exc: # noqa: BLE001
- discard_atomic_uv_install_generation(plan.activation.candidate_launcher)
- return {
- "ok": False,
- "message": "Upgrade candidate failed integrity verification",
- "output": str(exc),
- "restarting": False,
- }
+ activation_committed = activation_committed or plan.activation.committed
+ if not activation_committed:
+ discard_atomic_uv_install_generation(plan.activation.candidate_launcher)
+ return {
+ "ok": False,
+ "message": "Upgrade candidate failed integrity verification",
+ "output": str(exc),
+ "activation_notice": None,
+ "restarting": False,
+ }
+ deferred_activation = deferred_activation or (
+ os.name == "nt" and launcher_is_current_process(plan.activation.launcher)
+ )
+ activation_postcommit_error = str(exc)
+ logger.warning("Upgrade activation completed with a post-commit error", exc_info=True)
elif result.returncode != 0 and plan.activation is not None:
discard_atomic_uv_install_generation(plan.activation.candidate_launcher)
if result.returncode == 0 and plan.activation is None and plan.method == "pip":
@@ -6259,6 +6298,7 @@ def do_upgrade(auto_restart: bool = True) -> dict:
"ok": False,
"message": "Upgrade installed an incomplete Python environment",
"output": integrity.detail,
+ "activation_notice": None,
"restarting": False,
}
if result.returncode == 0 and auto_restart and runtime_was_running and not deferred_activation:
@@ -6275,11 +6315,37 @@ def do_upgrade(auto_restart: bool = True) -> dict:
restart_failed = True
runtime_output = f"Restart scheduling failed; run `vibe restart` to use the new version.\n{exc}"
if result.returncode == 0:
+ if deferred_activation_log_error is not None:
+ return {
+ "ok": True,
+ "message": "Upgrade successful. Activation will complete after this process exits.",
+ "output": _append_upgrade_output(result.stdout, deferred_activation_log_error),
+ "activation_notice": None,
+ "restarting": auto_restart and runtime_was_running,
+ }
if deferred_activation:
+ try:
+ activation_notice = format_deferred_activation_log(
+ deferred_activation_log,
+ _configured_backend_language(),
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Deferred activation notice could not be formatted", exc_info=True)
+ return {
+ "ok": True,
+ "message": "Upgrade successful. Activation will complete after this process exits.",
+ "output": _append_upgrade_output(result.stdout, str(exc)),
+ "activation_notice": None,
+ "restarting": auto_restart and runtime_was_running,
+ }
return {
"ok": True,
"message": "Upgrade successful. Activation will complete after this process exits.",
- "output": _append_upgrade_output(result.stdout, None),
+ "output": _append_upgrade_output(
+ result.stdout,
+ activation_notice,
+ ),
+ "activation_notice": activation_notice,
"restarting": auto_restart and runtime_was_running,
}
if not restarting and not restart_failed:
@@ -6291,10 +6357,31 @@ def do_upgrade(auto_restart: bool = True) -> dict:
else:
message = "Upgrade successful. Please restart vibe."
+ output = _append_upgrade_output(result.stdout, runtime_output)
+ if activation_postcommit_error:
+ output = _append_upgrade_output(
+ output,
+ f"Upgrade activation cleanup reported: {activation_postcommit_error}",
+ )
+ if activation_outcome is not None:
+ try:
+ activation_notice = format_activation_failures(
+ activation_outcome,
+ _configured_backend_language(),
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Activation notice could not be formatted", exc_info=True)
+ activation_notice = None
+ output = _append_upgrade_output(
+ output,
+ f"Stable launcher activation notice unavailable: {exc}",
+ )
+ output = _append_upgrade_output(output, activation_notice)
return {
"ok": True,
"message": message,
- "output": _append_upgrade_output(result.stdout, runtime_output),
+ "output": output,
+ "activation_notice": activation_notice,
"restarting": restarting,
}
else:
@@ -6302,21 +6389,41 @@ def do_upgrade(auto_restart: bool = True) -> dict:
"ok": False,
"message": "Upgrade failed",
"output": result.stderr or result.stdout,
+ "activation_notice": None,
"restarting": False,
}
except subprocess.TimeoutExpired:
if plan.activation is not None:
+ activation_committed = activation_committed or plan.activation.committed
+ if plan.activation is not None and not activation_committed:
discard_atomic_uv_install_generation(plan.activation.candidate_launcher)
return {
"ok": False,
"message": "Upgrade timed out",
"output": None,
+ "activation_notice": None,
"restarting": False,
}
except Exception as e:
if plan.activation is not None:
+ activation_committed = activation_committed or plan.activation.committed
+ if plan.activation is not None and not activation_committed:
discard_atomic_uv_install_generation(plan.activation.candidate_launcher)
- return {"ok": False, "message": str(e), "output": None, "restarting": False}
+ if activation_committed:
+ return {
+ "ok": True,
+ "message": "Upgrade successful.",
+ "output": str(e),
+ "activation_notice": None,
+ "restarting": restarting,
+ }
+ return {
+ "ok": False,
+ "message": str(e),
+ "output": None,
+ "activation_notice": None,
+ "restarting": restarting,
+ }
def _append_upgrade_output(output: str | None, runtime_output: str | None) -> str | None:
diff --git a/vibe/cli.py b/vibe/cli.py
index eb58b2fee..d4d851c9f 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -86,9 +86,12 @@ from vibe.upgrade import (
current_generation,
execute_upgrade_plan,
defer_upgrade_activation,
+ format_deferred_activation_log,
generation_downgrade,
get_latest_version_info,
get_safe_cwd,
+ format_activation_failures,
+ get_deferred_activation_log_path,
is_desktop_managed_runtime,
_launcher_generation,
_candidate_python,
@@ -574,6 +577,73 @@ def _configured_cli_language() -> str:
return "en"
+def _redirect_broken_diagnostic_stream(stream: Any) -> None:
+ """Keep interpreter shutdown from flushing a broken advisory stream."""
+
+ try:
+ stream_fd = stream.fileno()
+ except (AttributeError, OSError, ValueError):
+ return
+ try:
+ devnull_fd = os.open(os.devnull, os.O_WRONLY)
+ try:
+ os.dup2(devnull_fd, stream_fd)
+ finally:
+ os.close(devnull_fd)
+ except OSError:
+ return
+
+
+def _emit_upgrade_advisory(message: str | None, *, stream: Any = None) -> bool:
+ """Best-effort emission for diagnostics after activation has committed."""
+
+ if not message:
+ return True
+ target = sys.stdout if stream is None else stream
+ text = str(message)
+ try:
+ target.write(text)
+ if not text.endswith("\n"):
+ target.write("\n")
+ target.flush()
+ return True
+ except UnicodeEncodeError:
+ try:
+ encoding = getattr(target, "encoding", None) or "utf-8"
+ escaped = text.encode(encoding, errors="backslashreplace").decode(encoding)
+ target.write(escaped)
+ if not escaped.endswith("\n"):
+ target.write("\n")
+ target.flush()
+ return True
+ except Exception:
+ _redirect_broken_diagnostic_stream(target)
+ return False
+ except Exception:
+ _redirect_broken_diagnostic_stream(target)
+ return False
+
+
+def _emit_activation_notice(outcome: Any) -> None:
+ """Format and emit a peer activation notice without affecting the result."""
+
+ try:
+ notice = format_activation_failures(outcome, _configured_cli_language())
+ except Exception as exc: # noqa: BLE001
+ notice = f"Stable launcher activation notice unavailable: {exc}"
+ _emit_upgrade_advisory(notice)
+
+
+def _emit_deferred_activation_notice(log_path: Path | None) -> None:
+ """Format and emit the deferred helper log location best-effort."""
+
+ try:
+ notice = format_deferred_activation_log(log_path, _configured_cli_language())
+ except Exception as exc: # noqa: BLE001
+ notice = f"Deferred activation diagnostics unavailable: {exc}"
+ _emit_upgrade_advisory(notice)
+
+
def cmd_skill(args) -> int:
"""List or load Skills through Avibe's live resolver."""
@@ -15796,7 +15866,12 @@ def cmd_upgrade():
restart = None
restart_error = None
deferred_activation = False
+ deferred_activation_log = None
+ deferred_activation_log_error = None
restart_python = None
+ activation_outcome = None
+ activation_committed = False
+ activation_postcommit_error = None
try:
with atomic_upgrade_lock():
@@ -15820,20 +15895,33 @@ def cmd_upgrade():
candidate_result = verify_upgrade_candidate(plan.activation)
if not candidate_result.ok:
raise RuntimeError(candidate_result.detail)
- defer_upgrade_activation(
+ deferred_process = defer_upgrade_activation(
plan.activation,
parent_pid=os.getpid(),
restart_required=runtime_was_running,
prepare_show_runtime=not should_skip_show_runtime_prepare(),
)
+ activation_committed = True
deferred_activation = True
+ try:
+ deferred_activation_log = get_deferred_activation_log_path(deferred_process)
+ except Exception as exc: # noqa: BLE001
+ deferred_activation_log_error = str(exc)
else:
restart_python = _candidate_python(plan.activation.candidate_launcher)
- activate_upgrade_candidate(plan.activation)
+ activation_outcome = activate_upgrade_candidate(plan.activation)
+ activation_committed = True
except Exception as exc: # noqa: BLE001
- discard_atomic_uv_install_generation(plan.activation.candidate_launcher)
- print(f"\033[31mUpgrade candidate failed integrity verification: {exc}\033[0m")
- return 1
+ activation_committed = activation_committed or plan.activation.committed
+ if not activation_committed:
+ discard_atomic_uv_install_generation(plan.activation.candidate_launcher)
+ print(f"\033[31mUpgrade candidate failed integrity verification: {exc}\033[0m")
+ return 1
+ deferred_activation = deferred_activation or (
+ os.name == "nt" and launcher_is_current_process(plan.activation.launcher)
+ )
+ activation_postcommit_error = str(exc)
+ logger.warning("Upgrade activation completed with a post-commit error", exc_info=True)
elif result.returncode != 0 and plan.activation is not None:
discard_atomic_uv_install_generation(plan.activation.candidate_launcher)
if result.returncode == 0 and plan.activation is None and plan.method == "pip":
@@ -15853,23 +15941,39 @@ def cmd_upgrade():
except Exception as exc:
restart_error = exc
if result.returncode == 0:
+ if not deferred_activation and restart is None and restart_error is None:
+ _prepare_show_runtime_after_install(current_vibe_path)
print("\033[32mUpgrade successful!\033[0m")
+ if activation_postcommit_error:
+ _emit_upgrade_advisory(
+ f"Upgrade activated the new version, but post-activation cleanup reported: "
+ f"{activation_postcommit_error}"
+ )
+ if activation_outcome is not None:
+ _emit_activation_notice(activation_outcome)
if deferred_activation:
print("Upgrade validated; launcher activation will complete after this command exits.")
+ if deferred_activation_log_error is not None:
+ _emit_upgrade_advisory(
+ f"Deferred activation diagnostics unavailable: {deferred_activation_log_error}"
+ )
+ else:
+ _emit_deferred_activation_notice(deferred_activation_log)
if runtime_was_running:
print("Restart will be scheduled by the activation helper.")
return 0
if restart_error is not None:
- print("\033[33mUpgrade installed, but restart scheduling failed.\033[0m")
- print(f"Restart error: {restart_error}")
- print("Run `vibe restart` to use the new version.")
+ _emit_upgrade_advisory(
+ "\033[33mUpgrade installed, but restart scheduling failed.\033[0m\n"
+ f"Restart error: {restart_error}\n"
+ "Run `vibe restart` to use the new version."
+ )
return 2
if restart is not None:
print("Restart scheduled to use the new version.")
print(f"Job ID: {restart['job_id']}")
print("Run `vibe status` to inspect the restart result.")
else:
- _prepare_show_runtime_after_install(current_vibe_path)
print("Avibe was not running; the new version will be used next time you start it.")
return 0
else:
@@ -15877,7 +15981,21 @@ def cmd_upgrade():
return 1
except Exception as e:
if plan.activation is not None:
+ activation_committed = activation_committed or plan.activation.committed
+ if plan.activation is not None and not activation_committed:
discard_atomic_uv_install_generation(plan.activation.candidate_launcher)
+ if restart_error is not None:
+ _emit_upgrade_advisory(
+ "\033[33mUpgrade installed, but restart scheduling failed.\033[0m\n"
+ f"Restart error: {restart_error}\n"
+ "Run `vibe restart` to use the new version."
+ )
+ return 2
+ if activation_committed:
+ _emit_upgrade_advisory(
+ f"Upgrade activated the new version, but post-activation reporting failed: {e}"
+ )
+ return 0
print(f"\033[31mUpgrade failed: {e}\033[0m")
return 1
@@ -18407,6 +18525,9 @@ def _dispatch_deferred_upgrade_activation(argv: list[str]) -> int:
source_generation=source_generation,
)
activated = False
+ activation_outcome = None
+ activation_postcommit_error = None
+ prepare_show_runtime = False
try:
with atomic_upgrade_lock():
reason = activation_block_reason(activation)
@@ -18418,8 +18539,15 @@ def _dispatch_deferred_upgrade_activation(argv: list[str]) -> int:
discard_atomic_uv_install_generation(activation.candidate_launcher)
print("deferred upgrade activation was superseded by another activation", file=sys.stderr)
return 1
- activate_upgrade_candidate(activation)
- activated = True
+ try:
+ activation_outcome = activate_upgrade_candidate(activation)
+ activated = True
+ except Exception as exc:
+ activated = activation.committed
+ if not activated:
+ raise
+ activation_postcommit_error = str(exc)
+ logger.warning("Deferred activation completed with a post-commit error", exc_info=True)
if args.restart:
schedule_restart(
delay_seconds=0.0,
@@ -18428,7 +18556,10 @@ def _dispatch_deferred_upgrade_activation(argv: list[str]) -> int:
prepare_show_runtime=args.prepare_show_runtime,
python_executable=sys.executable,
)
+ elif args.prepare_show_runtime:
+ prepare_show_runtime = True
except Exception as exc:
+ activated = activated or activation.committed
if not activated:
discard_atomic_uv_install_generation(activation.candidate_launcher)
print(f"deferred upgrade activation failed: {exc}", file=sys.stderr)
@@ -18436,8 +18567,24 @@ def _dispatch_deferred_upgrade_activation(argv: list[str]) -> int:
print(f"deferred upgrade restart scheduling failed: {exc}", file=sys.stderr)
return 1
- if not args.restart and args.prepare_show_runtime:
- _prepare_show_runtime_after_install(args.launcher)
+ if prepare_show_runtime:
+ try:
+ _prepare_show_runtime_after_install(args.launcher)
+ except Exception as exc:
+ _emit_upgrade_advisory(
+ f"deferred upgrade Show Runtime preparation failed: {exc}",
+ stream=sys.stderr,
+ )
+ return 1
+
+ if activation_postcommit_error:
+ _emit_upgrade_advisory(
+ f"Deferred activation completed, but post-activation cleanup reported: "
+ f"{activation_postcommit_error}",
+ stream=sys.stderr,
+ )
+ if activation_outcome is not None:
+ _emit_activation_notice(activation_outcome)
return 0
@@ -18488,12 +18635,23 @@ def _dispatch_installer_activation(argv: list[str]) -> int:
previous_level = retention_logger.level
retention_logger.addHandler(handler)
retention_logger.setLevel(logging.INFO)
+ activation_committed = False
try:
- activate_installer_candidate(activation)
+ activation_outcome = activate_installer_candidate(activation)
+ activation_committed = True
+ _emit_activation_notice(activation_outcome)
except Exception as exc:
- discard_atomic_uv_install_generation(activation.candidate_launcher)
- print(f"installer activation failed: {exc}", file=sys.stderr)
- return 1
+ activation_committed = activation_committed or activation.committed
+ if not activation_committed:
+ discard_atomic_uv_install_generation(activation.candidate_launcher)
+ _emit_upgrade_advisory(f"installer activation failed: {exc}", stream=sys.stderr)
+ return 1
+ else:
+ _emit_upgrade_advisory(
+ f"installer activation completed, but post-activation reporting failed: {exc}",
+ stream=sys.stderr,
+ )
+ return 0
finally:
retention_logger.removeHandler(handler)
retention_logger.setLevel(previous_level)
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index dd1cdd810..0069b7f0e 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -505,6 +505,12 @@
"upgradeFailed": "Upgrade failed. Please check logs.",
"upgradeFailedShort": "Upgrade failed",
"upgradeFailedSlack": "❌ *Upgrade Failed*\n\nPlease check the logs for details.",
+ "stableLauncherRepairInstruction": "run `{repairCommand}` from the activated launcher",
+ "stableLauncherRepairPowerShellInstruction": "in PowerShell, run `{repairCommand}` from the activated launcher",
+ "stableLauncherActivationFailed": "Upgrade activated the new version, but could not move stable launcher {launcher}: {reason}\nAfter addressing the reported cause, {repairInstruction} to repair the remaining managed stable launchers.",
+ "stableLauncherActivationPermissionDenied": "Upgrade activated the new version, but could not move stable launcher {launcher} because its launcher file or directory is not writable ({reason}). Correct its permissions or ownership first, then {repairInstruction}.",
+ "stableLauncherActivationChanged": "Upgrade activated the new version, but could not move stable launcher {launcher} because it changed after discovery, so it was left untouched. Inspect that launcher and confirm its intended target or installation. After addressing it as needed, {repairInstruction} to repair other remaining managed stable launchers.",
+ "deferredActivationLog": "The deferred activation helper will record its result in {logPath}.",
"updating": "Updating Avibe...",
"updatingSlack": "⏳ *Updating Avibe...*\n\nPlease wait, the service will restart shortly.",
"restartRequired": "Upgrade complete. Please restart Avibe.",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 31d9d80a9..e5be5677f 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -505,6 +505,12 @@
"upgradeFailed": "升级失败,请检查日志。",
"upgradeFailedShort": "升级失败",
"upgradeFailedSlack": "❌ *升级失败*\n\n请检查日志获取详情。",
+ "stableLauncherRepairInstruction": "从已激活的启动器运行 `{repairCommand}`",
+ "stableLauncherRepairPowerShellInstruction": "请在 PowerShell 中从已激活的启动器运行 `{repairCommand}`",
+ "stableLauncherActivationFailed": "升级已激活新版本,但无法移动稳定启动器 {launcher}:{reason}\n请先处理所报告的原因,然后{repairInstruction},以修复其余仍受管理的稳定启动器。",
+ "stableLauncherActivationPermissionDenied": "升级已激活新版本,但无法移动稳定启动器 {launcher},因为启动器文件或目录不可写({reason})。请先修正其权限或所有者,然后{repairInstruction}。",
+ "stableLauncherActivationChanged": "升级已激活新版本,但无法移动稳定启动器 {launcher},因为它在发现后发生了变化,因此该启动器保持原样。请检查该启动器并确认其目标或安装状态;如有需要先处理它,然后{repairInstruction},以修复其他仍受管理的稳定启动器。",
+ "deferredActivationLog": "延迟激活助手会将结果记录到 {logPath}。",
"updating": "正在更新 Avibe...",
"updatingSlack": "⏳ *正在更新 Avibe...*\n\n请稍等,服务稍后会重启。",
"restartRequired": "升级完成,请重启 Avibe。",
diff --git a/vibe/upgrade.py b/vibe/upgrade.py
index 8c1a752c0..4decd5d5a 100644
--- a/vibe/upgrade.py
+++ b/vibe/upgrade.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import contextlib
+import errno
import json
import logging
import os
@@ -14,7 +15,7 @@ import time
import urllib.parse
import urllib.request
from collections.abc import Callable, Mapping
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import cast
@@ -188,13 +189,36 @@ def _pip_dry_run_is_unsupported(result: subprocess.CompletedProcess[str]) -> boo
)
-@dataclass(frozen=True)
+@dataclass
class AtomicActivation:
- """A validated candidate and the stable launcher it will replace."""
+ """A validated candidate and the stable launcher it will replace.
+
+ ``committed`` becomes true immediately after the stable launcher is
+ replaced. Callers use it to distinguish post-commit cleanup or reporting
+ failures from pre-commit activation failures.
+ """
launcher: Path
candidate_launcher: Path
source_generation: Path | None = None
+ committed: bool = field(default=False, init=False, repr=False, compare=False)
+
+
+@dataclass(frozen=True)
+class LauncherActivationFailure:
+ """A managed peer launcher that remained on its previous generation."""
+
+ launcher: Path
+ reason: str
+ reason_code: str = "move_failed"
+
+
+@dataclass(frozen=True)
+class ActivationOutcome:
+ """The committed activation and any managed peers left behind."""
+
+ activated_launcher: Path
+ peer_failures: tuple[LauncherActivationFailure, ...] = ()
def atomic_uv_install_root() -> Path:
@@ -390,9 +414,18 @@ def defer_upgrade_activation(
with contextlib.suppress(OSError):
process.terminate()
raise
+ activation.committed = True
+ setattr(process, "activation_log_path", log_path)
return process
+def get_deferred_activation_log_path(process: object) -> Path | None:
+ """Return the existing log path used by a detached activation helper."""
+
+ path = getattr(process, "activation_log_path", None)
+ return path if isinstance(path, Path) else None
+
+
def get_cli_launcher_path(launcher: runtime_mod.ServiceLauncher) -> Path | None:
"""Find the CLI launcher next to a saved service interpreter."""
@@ -852,16 +885,27 @@ def _prepare_launcher_replacement(replacement: Path, target: Path) -> None:
shutil.copy2(target, replacement)
-def activate_upgrade_candidate(activation: AtomicActivation) -> None:
+def _activation_failure_reason_code(exc: BaseException) -> str:
+ """Classify a peer move failure without discarding its concrete cause."""
+
+ if isinstance(exc, PermissionError) or getattr(exc, "errno", None) in {
+ errno.EACCES,
+ errno.EPERM,
+ } or getattr(exc, "winerror", None) == 5:
+ return "permission_denied"
+ return "move_failed"
+
+
+def activate_upgrade_candidate(activation: AtomicActivation) -> ActivationOutcome:
"""Atomically switch the stable launcher to a validated candidate."""
# Runtime callers already own this lock; the lock is re-entrant so direct
# activation and installer callers share the same collection boundary too.
with atomic_upgrade_lock():
- _activate_upgrade_candidate_locked(activation)
+ return _activate_upgrade_candidate_locked(activation)
-def _activate_upgrade_candidate_locked(activation: AtomicActivation) -> None:
+def _activate_upgrade_candidate_locked(activation: AtomicActivation) -> ActivationOutcome:
from vibe.install_generations import (
collect_install_generations,
finish_install_generation,
@@ -883,6 +927,7 @@ def _activate_upgrade_candidate_locked(activation: AtomicActivation) -> None:
try:
_prepare_launcher_replacement(replacement, activation.candidate_launcher)
os.replace(replacement, launcher)
+ activation.committed = True
except Exception:
with contextlib.suppress(OSError):
replacement.unlink()
@@ -892,17 +937,31 @@ def _activate_upgrade_candidate_locked(activation: AtomicActivation) -> None:
# `vibe doctor`; it must not undo the committed activation. A peer that
# now follows the primary, such as an alias of it, keeps its shape.
activated = _generation_for_path(activation.candidate_launcher, root)
+ peer_failures: list[LauncherActivationFailure] = []
for peer, selected in peers:
+ if selected == activated:
+ continue
try:
- if selected != activated:
- move_managed_launcher_locked(peer, selected, activation.candidate_launcher)
- except Exception:
+ if not move_managed_launcher_locked(peer, selected, activation.candidate_launcher):
+ if _launcher_generation(peer, root) == activated:
+ continue
+ reason = "the launcher changed after discovery"
+ peer_failures.append(
+ LauncherActivationFailure(peer, reason, "launcher_changed_after_discovery")
+ )
+ logger.warning("Could not move stable launcher %s: %s", peer, reason)
+ except Exception as exc:
+ reason = str(exc).strip() or type(exc).__name__
+ peer_failures.append(
+ LauncherActivationFailure(peer, reason, _activation_failure_reason_code(exc))
+ )
logger.warning("Could not move stable launcher %s to the activated generation", peer, exc_info=True)
finish_install_generation(activation.candidate_launcher)
collect_install_generations(launcher)
+ return ActivationOutcome(launcher.absolute(), tuple(peer_failures))
-def activate_installer_candidate(activation: AtomicActivation) -> None:
+def activate_installer_candidate(activation: AtomicActivation) -> ActivationOutcome:
"""Activate an installer candidate through the shared lifecycle owner."""
with atomic_upgrade_lock():
@@ -911,7 +970,63 @@ def activate_installer_candidate(activation: AtomicActivation) -> None:
raise RuntimeError("an Avibe restart is still in progress")
if reason == "superseded":
raise RuntimeError("the active Avibe generation changed while the installer was staging")
- activate_upgrade_candidate(activation)
+ return activate_upgrade_candidate(activation)
+
+
+def activation_repair_command(launcher: str | os.PathLike[str]) -> str:
+ """Return a shell-safe repair command rooted at the activated launcher."""
+
+ full_path = os.path.abspath(os.path.expanduser(str(launcher)))
+ command = [full_path, "doctor", "repair", "stable-launchers"]
+ if os.name == "nt":
+ powershell_path = full_path.replace("'", "''")
+ return f"& '{powershell_path}' doctor repair stable-launchers"
+ return shlex.join(command)
+
+
+def format_activation_failures(outcome: ActivationOutcome, language: str = "en") -> str | None:
+ """Render managed peer failures for a user-facing upgrade result."""
+
+ if not outcome.peer_failures:
+ return None
+ from vibe.i18n import t
+
+ repair_command = activation_repair_command(outcome.activated_launcher)
+ repair_instruction_key = (
+ "update.stableLauncherRepairPowerShellInstruction"
+ if os.name == "nt"
+ else "update.stableLauncherRepairInstruction"
+ )
+ repair_instruction = t(repair_instruction_key, language, repairCommand=repair_command)
+ messages = []
+ for failure in outcome.peer_failures:
+ if failure.reason_code == "permission_denied":
+ key = "update.stableLauncherActivationPermissionDenied"
+ elif failure.reason_code == "launcher_changed_after_discovery":
+ key = "update.stableLauncherActivationChanged"
+ else:
+ key = "update.stableLauncherActivationFailed"
+ messages.append(
+ t(
+ key,
+ language,
+ launcher=str(failure.launcher),
+ reason=failure.reason,
+ repairCommand=repair_command,
+ repairInstruction=repair_instruction,
+ )
+ )
+ return "\n\n".join(messages)
+
+
+def format_deferred_activation_log(log_path: Path | None, language: str = "en") -> str | None:
+ """Explain where a deferred activation helper records its result."""
+
+ if log_path is None:
+ return None
+ from vibe.i18n import t
+
+ return t("update.deferredActivationLog", language, logPath=str(log_path))
def activate_launcher_target(launcher: str | os.PathLike[str], target: str | os.PathLike[str]) -> None: