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(agents): restore a backend CLI an unattended upgrade left unable to start (#3080)

Call Whitef19391fcfd10
diff --git a/core/update_checker.py b/core/update_checker.py
index 45d7a7beb..e4f12a42b 100644
--- a/core/update_checker.py
+++ b/core/update_checker.py
@@ -49,6 +49,14 @@ UPDATE_BUTTON_ACTION_ID = "vibe_update_now"
MIN_CHECK_INTERVAL_MINUTES = 1
MANAGED_DEPENDENCY_CHECK_INTERVAL_MINUTES = 60
+# A backend CLI release is installed unattended only once it has been seen for this
+# long. A package can be visible before its whole release is: Codex 0.166.0 published
+# its macOS arm64 binary 3 minutes, and its Windows arm64 one 19 minutes, after the
+# version npm called latest, and npm installs a missing optional binary as success.
+BACKEND_RELEASE_SETTLE_SECONDS = 6 * 3600
+# Unattended installs of one backend release, each on its own check.
+BACKEND_AUTO_UPDATE_MAX_ATTEMPTS = 3
+
# Grace period after sending an update notification before auto-update can proceed (in minutes).
# This gives admins time to read the notification and decide whether to update manually.
NOTIFICATION_GRACE_PERIOD_MINUTES = 10
@@ -144,6 +152,26 @@ def _format_release_version_link(version: str, platform: str = "markdown") -> st
return f"[{version_text}]({url})"
+def _backend_attempts(value: Any) -> Dict[str, Dict[str, Any]]:
+ """Released versions recorded one failed release per backend as its version string."""
+ attempts: Dict[str, Dict[str, Any]] = {}
+ for name, entry in (value or {}).items() if isinstance(value, dict) else ():
+ if isinstance(entry, str):
+ entry = {"version": entry, "count": 1}
+ if isinstance(entry, dict) and isinstance(entry.get("version"), str) and type(entry.get("count")) is int:
+ attempts[str(name)] = {"version": entry["version"], "count": entry["count"]}
+ return attempts
+
+
+def _backend_releases_seen(value: Any) -> Dict[str, Dict[str, Any]]:
+ seen: Dict[str, Dict[str, Any]] = {}
+ for name, entry in (value or {}).items() if isinstance(value, dict) else ():
+ at = entry.get("at") if isinstance(entry, dict) else None
+ if isinstance(entry, dict) and isinstance(entry.get("version"), str) and type(at) in (int, float):
+ seen[str(name)] = {"version": entry["version"], "at": float(at)}
+ return seen
+
+
@dataclass
class UpdateState:
"""Persistent state for update tracking."""
@@ -156,9 +184,11 @@ class UpdateState:
blocked_auto_update_reason: Optional[str] = None
blocked_auto_update_at: Optional[str] = None
blocked_auto_update_current_version: Optional[str] = None
- # Backend name -> the release its unattended upgrade last ran for, so a
- # release that fails to install is not retried on every check.
- backend_auto_update_attempts: Dict[str, str] = field(default_factory=dict)
+ # Backend name -> {"version", "count"}: the failed unattended installs of the
+ # release last tried, so one that keeps failing stops being retried.
+ backend_auto_update_attempts: Dict[str, Dict[str, Any]] = field(default_factory=dict)
+ # Backend name -> {"version", "at"}: when the backend's latest release was first seen.
+ backend_releases_seen: Dict[str, Dict[str, Any]] = field(default_factory=dict)
@classmethod
def load(cls) -> "UpdateState":
@@ -167,7 +197,6 @@ class UpdateState:
return cls()
try:
data = json.loads(path.read_text(encoding="utf-8"))
- attempts = data.get("backend_auto_update_attempts")
return cls(
notified_version=data.get("notified_version"),
notified_at=data.get("notified_at"),
@@ -177,11 +206,8 @@ class UpdateState:
blocked_auto_update_reason=data.get("blocked_auto_update_reason"),
blocked_auto_update_at=data.get("blocked_auto_update_at"),
blocked_auto_update_current_version=data.get("blocked_auto_update_current_version"),
- backend_auto_update_attempts=(
- {str(name): str(version) for name, version in attempts.items()}
- if isinstance(attempts, dict)
- else {}
- ),
+ backend_auto_update_attempts=_backend_attempts(data.get("backend_auto_update_attempts")),
+ backend_releases_seen=_backend_releases_seen(data.get("backend_releases_seen")),
)
except Exception as e:
logger.warning(f"Failed to load update state: {e}")
@@ -201,6 +227,7 @@ class UpdateState:
"blocked_auto_update_at": self.blocked_auto_update_at,
"blocked_auto_update_current_version": self.blocked_auto_update_current_version,
"backend_auto_update_attempts": self.backend_auto_update_attempts,
+ "backend_releases_seen": self.backend_releases_seen,
}
write_atomic(path, json.dumps(data, indent=2))
except Exception as e:
@@ -520,7 +547,14 @@ class UpdateChecker:
logger.warning("askill managed dependency reconcile raised: %s", exc, exc_info=True)
async def _reconcile_backend_auto_updates(self) -> None:
- """Upgrade opted-in backend CLIs, each only while no turn is using it."""
+ """Upgrade opted-in backend CLIs, each only while no turn is using it.
+
+ A CLI the installer leaves unable to start is restored at once: npm
+ reports an install whose native binary failed to download as a success,
+ so an upgrade can turn a working CLI into one that cannot run. A broken
+ CLI is repaired, a release is installed only once it has settled, and
+ each release gets a bounded number of attempts.
+ """
coordinator = getattr(self.controller, "backend_restart_coordinator", None)
if coordinator is None:
return
@@ -534,47 +568,91 @@ class UpdateChecker:
try:
runtime = await asyncio.to_thread(api.get_backend_runtime, backend)
latest = runtime.get("latest_version")
+ broken = runtime.get("status") == "broken"
if not (
runtime.get("ok")
and runtime.get("enabled")
and runtime.get("auto_update")
and runtime.get("installed")
- and runtime.get("has_update")
+ and (broken or runtime.get("has_update"))
and latest
- ) or self.state.backend_auto_update_attempts.get(backend) == latest:
+ ):
+ continue
+ if not broken and not self._backend_release_settled(backend, latest):
+ continue
+ attempt = self.state.backend_auto_update_attempts.get(backend)
+ if attempt and attempt["version"] == latest and attempt["count"] >= BACKEND_AUTO_UPDATE_MAX_ATTEMPTS:
continue
# Checked per backend: a message may arrive during an earlier install.
if not self._quiet_for_idle_window():
return
+ # The release that runs now, which a failed upgrade restores.
+ working = None if broken else runtime.get("current_version")
- async def install(name: str = backend, release: str = latest) -> dict:
+ async def install(name: str = backend, release: str = latest, previous: Optional[str] = working) -> dict:
try:
- result = await asyncio.to_thread(api.install_agent, name)
+ # Pinned: the installer must not take a newer release that has not settled.
+ result = await asyncio.to_thread(api.install_agent, name, version=release)
except Exception as exc: # noqa: BLE001
result = {"ok": False, "message": str(exc) or type(exc).__name__}
- # A failed release is not retried unattended. It is recorded
- # before the refresh, whose own failure must not undo that.
- # A success needs no record: the next check sees whether it
- # actually reached the release, and tries again if not.
- if not result.get("ok") and result.get("code") != "install_locked":
- self.state.backend_auto_update_attempts[name] = release
- self.state.save()
+ if result.get("ok") or result.get("code") == "install_locked":
+ return result
+ # Recorded before the restore and the refresh, whose own failures must
+ # not undo it. A success needs no record: the next check sees whether
+ # it actually reached the release, and tries again if not.
+ attempt = self.state.backend_auto_update_attempts.get(name)
+ count = attempt["count"] + 1 if attempt and attempt["version"] == release else 1
+ self.state.backend_auto_update_attempts[name] = {"version": release, "count": count}
+ self.state.save()
+ if previous:
+ result = {**result, "restore": await self._restore_backend(name, previous)}
return result
result = await coordinator.run_when_idle(backend, install)
+ action = "repair" if broken else f"auto-update to {latest}"
if result is None:
- logger.info("Backend %s auto-update to %s deferred: backend is busy", backend, latest)
+ logger.info("Backend %s %s deferred: backend is busy", backend, action)
elif result.get("code") == "install_locked":
- logger.info("Backend %s auto-update to %s deferred: another install is running", backend, latest)
+ logger.info("Backend %s %s deferred: another install is running", backend, action)
elif not result.get("ok"):
- logger.warning("Backend %s auto-update to %s failed: %s", backend, latest, result.get("message"))
+ logger.warning("Backend %s %s failed: %s", backend, action, result.get("message"))
elif (await asyncio.to_thread(api.get_backend_runtime, backend)).get("has_update"):
logger.info("Backend %s installer left it behind %s; retrying on a later check", backend, latest)
else:
- logger.info("Backend %s auto-updated to %s", backend, latest)
+ logger.info("Backend %s %s succeeded", backend, action)
except Exception as exc: # noqa: BLE001
logger.warning("Backend %s auto-update failed: %s", backend, exc, exc_info=True)
+ def _backend_release_settled(self, backend: str, release: str) -> bool:
+ """Whether ``release`` has been seen for ``BACKEND_RELEASE_SETTLE_SECONDS``; records when it first was."""
+ seen = self.state.backend_releases_seen.get(backend)
+ now = time.time()
+ if seen is None or seen["version"] != release:
+ self.state.backend_releases_seen[backend] = {"version": release, "at": now}
+ self.state.save()
+ return False
+ return now - seen["at"] >= BACKEND_RELEASE_SETTLE_SECONDS
+
+ async def _restore_backend(self, name: str, previous: str) -> str:
+ """Put back the release that ran before a failed upgrade left the CLI unable to start or removed it."""
+ from vibe import api
+
+ try:
+ runtime = await asyncio.to_thread(api.get_backend_runtime, name)
+ # An installer that failed or timed out can also leave no launcher at all.
+ if runtime.get("status") not in {"broken", "missing"}:
+ return "not_needed"
+ restored = await asyncio.to_thread(api.install_agent, name, version=previous)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Backend %s restore after a failed upgrade raised: %s", name, exc)
+ return "failed"
+ if restored.get("ok"):
+ logger.warning("Backend %s upgrade left it unable to start; restored %s", name, previous)
+ return "restored"
+ logger.error("Backend %s upgrade left it unable to start, and restoring %s failed: %s",
+ name, previous, restored.get("message"))
+ return "failed"
+
async def _get_version_info_async(self) -> Dict[str, Any]:
"""Get version info asynchronously."""
return await asyncio.to_thread(_fetch_pypi_version_sync)
diff --git a/tests/test_cli_repair.py b/tests/test_cli_repair.py
index 265100a60..4c49cf9c0 100644
--- a/tests/test_cli_repair.py
+++ b/tests/test_cli_repair.py
@@ -232,8 +232,10 @@ def test_npm_provenance_preserves_global_prefix(tmp_path, backend, package):
("opencode", "opencode-ai", "1.2.15"),
],
)
+# A repair can pin the release an unattended upgrade replaced (core.update_checker).
[email protected]("repair_version", [None, "1.0.0"])
def test_broken_npm_cli_is_repaired_by_its_prefix_not_self_update(
- native_case, monkeypatch, backend, package, version_output
+ native_case, monkeypatch, backend, package, version_output, repair_version
):
c = native_case
prefix = c["home"] / "owned npm prefix"
@@ -256,9 +258,10 @@ def test_broken_npm_cli_is_repaired_by_its_prefix_not_self_update(
)
monkeypatch.setattr(api, "_configured_agent_cli_path", lambda _name: str(alias))
monkeypatch.setattr(api, "resolve_cli_path", lambda name, **_: str(npm) if name == "npm" else str(alias))
- result = api.install_agent(backend)
+ result = api.install_agent(backend, version=repair_version)
assert result["ok"], result
- assert json.loads(calls.read_text()) == ["install", "--global", "--prefix", str(prefix), package]
+ spec = f"{package}@{repair_version}" if repair_version else package
+ assert json.loads(calls.read_text()) == ["install", "--global", "--prefix", str(prefix), spec]
assert old.read_text().splitlines() == ["--version"]
assert c["persist"] == [(backend, str(alias))]
assert result["detection"]["status"] == "ok" and result["detection"]["path"] == str(alias)
@@ -318,8 +321,12 @@ def test_healthy_upgrade_certifies_only_the_selected_executable(native_case, mon
@pytest.mark.parametrize("fresh", [False, True])
@pytest.mark.parametrize("outcome", ["missing", "broken", "healthy"])
-def test_codex_npm_certifies_its_declared_prefix_not_an_old_healthy_cli(native_case, monkeypatch, fresh, outcome):
[email protected]("version", [None, "0.162.1"])
+def test_codex_npm_certifies_its_declared_prefix_not_an_old_healthy_cli(
+ native_case, monkeypatch, fresh, outcome, version
+):
c = native_case
+ calls = c["home"] / "npm-install-args.json"
old = executable(c["home"] / "old/lib/node_modules/@openai/codex/bin/codex.js", 'print("codex-cli 0.161.0")\n')
destination = c["home"] / ".local/bin/codex"
installed = c["home"] / "npm-finished"
@@ -339,6 +346,7 @@ def test_codex_npm_certifies_its_declared_prefix_not_an_old_healthy_cli(native_c
c["tools"] / "npm",
'import os,sys\nfrom pathlib import Path\nif sys.argv[1:]==["config","get","prefix"]:\n print("/fixture/different-global-prefix");sys.exit(0)\n'
+ install_body
+ + f"Path({str(calls)!r}).write_text(__import__('json').dumps(sys.argv[1:]))\n"
+ f"Path({str(installed)!r}).touch()\n",
)
configured = "codex" if fresh else str(old)
@@ -356,8 +364,11 @@ def test_codex_npm_certifies_its_declared_prefix_not_an_old_healthy_cli(native_c
return str(old) if binary in {"codex", str(old)} else None
monkeypatch.setattr(api, "resolve_cli_path", resolve)
- result = api.install_agent("codex")
+ result = api.install_agent("codex", version=version)
assert installed.exists()
+ # A pinned upgrade installs that release, not whatever npm calls latest by then.
+ spec = f"@openai/codex@{version}" if version else "@openai/codex"
+ assert json.loads(calls.read_text()) == ["install", "-g", spec]
assert old.exists() # the old selected/discovered CLI is still healthy
assert api.resolve_cli_path("codex") == str(old) # old fallback would certify it
if outcome == "healthy":
diff --git a/tests/test_update_checker_platforms.py b/tests/test_update_checker_platforms.py
index 8423b40b5..430c6918a 100644
--- a/tests/test_update_checker_platforms.py
+++ b/tests/test_update_checker_platforms.py
@@ -1171,7 +1171,13 @@ def _backend_auto_update_checker(monkeypatch, tmp_path, sqlite_schema_db_factory
return checker
-def test_backend_auto_update_retries_a_release_until_it_lands_or_its_install_fails(
+def _settled(checker, **releases):
+ """Releases first seen long enough ago to install unattended."""
+ seen_at = time.time() - update_checker.BACKEND_RELEASE_SETTLE_SECONDS - 1
+ checker.state.backend_releases_seen = {name: {"version": v, "at": seen_at} for name, v in releases.items()}
+
+
+def test_backend_auto_update_retries_a_release_until_it_lands_or_its_attempts_run_out(
monkeypatch, tmp_path, sqlite_schema_db_factory
):
admissions = []
@@ -1188,26 +1194,34 @@ def test_backend_auto_update_retries_a_release_until_it_lands_or_its_install_fai
return result
runtimes = {
- "codex": {"auto_update": True, "has_update": True, "latest_version": "1.1.0"},
- "claude": {"auto_update": False, "has_update": True, "latest_version": "2.0.0"},
- "opencode": {"auto_update": True, "has_update": False, "latest_version": "1.0.0"},
+ "codex": {"auto_update": True, "has_update": True, "latest_version": "1.1.0", "status": "ok"},
+ "claude": {"auto_update": False, "has_update": True, "latest_version": "2.0.0", "status": "ok"},
+ "opencode": {"auto_update": True, "has_update": False, "latest_version": "1.0.0", "status": "ok"},
}
install_results = [
{"ok": False, "code": "install_locked", "message": "Another Codex installation is already running."},
{"ok": True},
{"ok": False, "code": "install_failed", "message": "Could not upgrade Codex."},
+ {"ok": False, "code": "install_failed", "message": "Could not upgrade Codex."},
+ {"ok": False, "code": "install_failed", "message": "Could not upgrade Codex."},
{"ok": True},
]
installs = []
- def install(name):
- installs.append(name)
+ def install(name, **kwargs):
+ installs.append((name, kwargs))
return install_results.pop(0)
checker = _backend_auto_update_checker(
monkeypatch, tmp_path, sqlite_schema_db_factory, _Coordinator(), runtimes, install
)
+ # A release just published waits until it has settled.
+ asyncio.run(checker._do_check())
+ assert admissions == []
+ assert checker.state.backend_releases_seen["codex"]["version"] == "1.1.0"
+ _settled(checker, codex="1.1.0")
+
# A message inside the quiet window defers every backend, like Avibe's own update.
checker.state.last_activity_at = time.time() - 60
asyncio.run(checker._do_check())
@@ -1221,16 +1235,113 @@ def test_backend_auto_update_retries_a_release_until_it_lands_or_its_install_fai
coordinator_state["refresh_fails"] = True
asyncio.run(checker._do_check()) # the install fails, then so does the refresh
coordinator_state["refresh_fails"] = False
- asyncio.run(checker._do_check()) # the failed release is not retried
-
- assert admissions == ["codex"] * 4
- assert installs == ["codex"] * 3
- assert update_checker.UpdateState.load().backend_auto_update_attempts == {"codex": "1.1.0"}
+ asyncio.run(checker._do_check()) # the second attempt fails
+ asyncio.run(checker._do_check()) # the third attempt fails
+ asyncio.run(checker._do_check()) # the release is not tried a fourth time
+
+ assert admissions == ["codex"] * 6
+ # Each install is pinned to the release that settled, never whatever is latest by then.
+ assert installs == [("codex", {"version": "1.1.0"})] * 5
+ assert update_checker.UpdateState.load().backend_auto_update_attempts == {
+ "codex": {"version": "1.1.0", "count": 3}
+ }
runtimes["codex"]["latest_version"] = "1.2.0"
- asyncio.run(checker._do_check()) # a newer release is tried again
+ asyncio.run(checker._do_check()) # a newer release settles first
+ _settled(checker, codex="1.2.0")
+ asyncio.run(checker._do_check()) # and is then tried again
+
+ assert installs[-1] == ("codex", {"version": "1.2.0"})
+
+
+# An installer can also fail or time out after removing the launcher.
[email protected]("left", ["broken", "missing"])
+def test_an_upgrade_that_leaves_the_cli_unable_to_start_restores_the_release_it_replaced(
+ monkeypatch, tmp_path, sqlite_schema_db_factory, left
+):
+ """npm reports an install whose native binary failed to download as a success, so the
+ upgrade's readback finds a CLI that cannot start: Codex 0.166.0 left one on a
+ machine that had run 0.165.0. The working release goes back in the same idle
+ window, and the upgrade is tried again on a later check."""
+
+ class _Coordinator:
+ async def run_when_idle(self, backend, operation):
+ return await operation()
+
+ codex = {"auto_update": True, "has_update": True, "latest_version": "0.166.0",
+ "current_version": "0.165.0", "status": "ok"}
+ runtimes = {
+ "codex": codex,
+ "claude": {"auto_update": False, "status": "ok"},
+ "opencode": {"auto_update": False, "status": "ok"},
+ }
+ installs = []
+
+ def install(name, version=None):
+ installs.append(version)
+ if version == "0.166.0": # the upgrade: npm exits 0 without the binary
+ codex.update(status=left, installed=left != "missing", current_version=None, has_update=False)
+ return {"ok": False, "code": "cli_readback_failed", "message": "cannot start"}
+ codex.update(status="ok", installed=True, current_version=version, has_update=True)
+ return {"ok": True}
+
+ checker = _backend_auto_update_checker(
+ monkeypatch, tmp_path, sqlite_schema_db_factory, _Coordinator(), runtimes, install
+ )
+ _settled(checker, codex="0.166.0")
+
+ asyncio.run(checker._do_check())
+
+ # The upgrade is pinned to the release that settled, the restore to the one it replaced.
+ assert installs == ["0.166.0", "0.165.0"]
+ assert (codex["status"], codex["current_version"]) == ("ok", "0.165.0")
+ assert checker.state.backend_auto_update_attempts == {"codex": {"version": "0.166.0", "count": 1}}
+
+ def upgrade(name, version=None):
+ installs.append(version)
+ codex.update(current_version="0.166.0", has_update=False)
+ return {"ok": True}
+
+ monkeypatch.setattr("vibe.api.install_agent", upgrade)
+ asyncio.run(checker._do_check())
+
+ assert installs == ["0.166.0", "0.165.0", "0.166.0"]
+ assert codex["current_version"] == "0.166.0"
+
+
+def test_a_cli_that_cannot_start_is_repaired_without_waiting_for_a_release(
+ monkeypatch, tmp_path, sqlite_schema_db_factory
+):
+ """A CLI broken before this check (by an earlier upgrade, or by hand) has no version to
+ compare, so it never looked outdated and was never touched again."""
+
+ class _Coordinator:
+ async def run_when_idle(self, backend, operation):
+ return await operation()
+
+ codex = {"auto_update": True, "has_update": False, "latest_version": "0.166.0",
+ "current_version": None, "status": "broken"}
+ runtimes = {
+ "codex": codex,
+ "claude": {"auto_update": True, "has_update": False, "latest_version": "2.0.0", "status": "missing"},
+ "opencode": {"auto_update": False, "status": "ok"},
+ }
+ installs = []
+
+ def install(name, version=None):
+ installs.append((name, version))
+ return {"ok": False, "code": "cli_readback_failed", "message": "cannot start"}
+
+ checker = _backend_auto_update_checker(
+ monkeypatch, tmp_path, sqlite_schema_db_factory, _Coordinator(), runtimes, install
+ )
+
+ for _ in range(4):
+ asyncio.run(checker._do_check())
- assert installs == ["codex"] * 4
+ # The repair reinstalls the latest release through install_agent, which repairs a broken
+ # CLI; it has no working release to restore, and stops after the release's attempts.
+ assert installs == [("codex", "0.166.0")] * update_checker.BACKEND_AUTO_UPDATE_MAX_ATTEMPTS
def test_backend_auto_update_stops_admitting_backends_once_a_message_arrives(
@@ -1243,26 +1354,35 @@ def test_backend_auto_update_stops_admitting_backends_once_a_message_arrives(
admissions.append(backend)
return await operation()
- def install(name):
+ def install(name, **_kwargs):
# The first backend's install outlasts the quiet window.
checker.record_activity()
return {"ok": True}
runtimes = {
- name: {"auto_update": True, "has_update": True, "latest_version": "9.0.0"}
+ name: {"auto_update": True, "has_update": True, "latest_version": "9.0.0", "status": "ok"}
for name in ("codex", "claude", "opencode")
}
checker = _backend_auto_update_checker(
monkeypatch, tmp_path, sqlite_schema_db_factory, _Coordinator(), runtimes, install
)
+ _settled(checker, codex="9.0.0", claude="9.0.0", opencode="9.0.0")
asyncio.run(checker._do_check())
assert len(admissions) == 1
[email protected]("attempts", [None, ["codex"]])
-def test_update_state_without_backend_attempts_loads_released_fields(monkeypatch, tmp_path, attempts):
+ "attempts,loaded",
+ [
+ (None, {}),
+ (["codex"], {}),
+ # Released versions recorded the one failed release as its version string.
+ ({"codex": "0.166.0"}, {"codex": {"version": "0.166.0", "count": 1}}),
+ ],
+)
+def test_update_state_without_backend_attempts_loads_released_fields(monkeypatch, tmp_path, attempts, loaded):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
released = {
"notified_version": "3.0.3",
@@ -1284,4 +1404,5 @@ def test_update_state_without_backend_attempts_loads_released_fields(monkeypatch
assert state.notified_version == "3.0.3"
assert state.last_activity_at == 1767225600.0
- assert state.backend_auto_update_attempts == {}
+ assert state.backend_auto_update_attempts == loaded
+ assert state.backend_releases_seen == {}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index b5fa29eda..ada23937c 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -3957,7 +3957,7 @@
"restartSuccess": "Restart requested",
"restartFailed": "Restart failed",
"autoUpdate": "Auto Update",
- "autoUpdateHint": "Install new releases once this backend is idle"
+ "autoUpdateHint": "Install a new release once it has been out for 6 hours and this backend is idle; a CLI that cannot start is repaired"
},
"channelList": {
"eyebrow": "Groups",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 678d6ed00..99913dba6 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -3957,7 +3957,7 @@
"restartSuccess": "已请求重启",
"restartFailed": "重启失败",
"autoUpdate": "自动更新",
- "autoUpdateHint": "该后端空闲时自动安装新版本"
+ "autoUpdateHint": "新版本发布满 6 小时后,在该后端空闲时自动安装;无法启动的 CLI 会被自动修复"
},
"channelList": {
"eyebrow": "群组",
diff --git a/vibe/api.py b/vibe/api.py
index 15453c01d..dcd34c3d6 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -651,7 +651,9 @@ def _codex_cli_supports_update(codex_path: str) -> bool:
return re.search(r"(?m)^\s*update\s+", output) is not None
-def _codex_upgrade_command(existing_path: str) -> tuple[list[str], dict[str, str] | None] | dict:
+def _codex_upgrade_command(
+ existing_path: str, *, version: str | None = None
+) -> tuple[list[str], dict[str, str] | None] | dict:
brew_path = resolve_cli_path("brew")
npm_install = _is_npm_codex_install(existing_path)
if brew_path:
@@ -689,7 +691,9 @@ def _codex_upgrade_command(existing_path: str) -> tuple[list[str], dict[str, str
"message": "Codex npm global prefix could not be determined; no upgrade was started.",
"output": None,
}
- return [npm_path, "install", "-g", "@openai/codex"], command_env
+ # Unversioned, npm installs whatever is ``latest`` now, which may be newer
+ # than the release the caller approved.
+ return [npm_path, "install", "-g", f"@openai/codex@{version}" if version else "@openai/codex"], command_env
if _codex_cli_supports_update(existing_path):
return [existing_path, "update"], None
@@ -8146,11 +8150,15 @@ def _run_desktop_backend_install(name: str, truncate_output) -> dict:
}
-def install_agent(name: str) -> dict:
+def install_agent(name: str, *, version: str | None = None) -> dict:
"""Install (or upgrade) an agent CLI tool, one install per backend at a time.
Settings runs this in the UI process and backend auto-update in the
controller, so only a file lock keeps two installers off one CLI.
+ ``version`` pins the release where the installation's source can: a Codex
+ npm install or upgrade, and a repair of a broken npm installation. Backend
+ auto-update passes the release it approved, or the one a failed upgrade
+ replaced. Self-updaters and Homebrew install what their source publishes.
"""
if not supports_install(name):
return {"ok": False, "message": f"Unknown agent: {name}"}
@@ -8166,7 +8174,7 @@ def install_agent(name: str) -> dict:
"path": None,
}
try:
- return _install_agent(name)
+ return _install_agent(name, version=version)
finally:
lock.release()
@@ -8181,7 +8189,7 @@ def _cli_repair_refusal(name: str, *, conflict: bool = False) -> dict:
}
-def _repair_broken_cli(name: str, selected: str, truncate_output) -> dict:
+def _repair_broken_cli(name: str, selected: str, truncate_output, *, version: str | None = None) -> dict:
source = identify_repair_source(name, selected)
if source is None:
return _cli_repair_refusal(name)
@@ -8190,7 +8198,10 @@ def _repair_broken_cli(name: str, selected: str, truncate_output) -> dict:
npm = resolve_cli_path("npm")
if not npm:
return _cli_repair_refusal(name)
- cmd = [npm, "install", "--global", "--prefix", str(source.prefix), source.package]
+ # A pinned release is the one npm already fetched whole for this
+ # platform; its native package is in the npm cache.
+ package = f"{source.package}@{version}" if version else source.package
+ cmd = [npm, "install", "--global", "--prefix", str(source.prefix), package]
command_env = _command_env_for(npm)
elif source.kind == "brew":
brew = source.prefix / "bin" / "brew"
@@ -8240,7 +8251,7 @@ def _native_vendor_install_target(name: str) -> str | None:
return None
-def _install_agent(name: str) -> dict:
+def _install_agent(name: str, *, version: str | None = None) -> dict:
"""Install (or upgrade) an agent CLI tool.
Existing installations keep their install method and their selected
@@ -8332,7 +8343,7 @@ def _install_agent(name: str) -> dict:
if health["status"] in {"broken", "unknown"} or (health["status"] == "missing" and configured_path != name):
if health["status"] == "unknown":
return _cli_repair_refusal(name)
- return _repair_broken_cli(name, health["path"] or configured_path, _truncate_output)
+ return _repair_broken_cli(name, health["path"] or configured_path, _truncate_output, version=version)
existing_path = health["path"]
if existing_path:
readback_validator = None
@@ -8353,7 +8364,7 @@ def _install_agent(name: str) -> dict:
cmd = [existing_path, "upgrade"]
command_env = None
elif name == "codex":
- upgrade = _codex_upgrade_command(existing_path)
+ upgrade = _codex_upgrade_command(existing_path, version=version)
if isinstance(upgrade, dict):
return upgrade
cmd, command_env = upgrade
@@ -8421,7 +8432,7 @@ def _install_agent(name: str) -> dict:
# package source that does not require OS package-manager privileges.
npm_path = resolve_cli_path("npm")
if npm_path:
- cmd = [npm_path, "install", "-g", "@openai/codex"]
+ cmd = [npm_path, "install", "-g", f"@openai/codex@{version}" if version else "@openai/codex"]
command_env = _codex_npm_install_env(npm_path)
if command_env is None:
return {