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): verify selected CLI health and repair outcomes (#2497)

Call White44b6f2a0cbf5
diff --git a/core/command_runner.py b/core/command_runner.py
index 6f966d5fa..569dd2c11 100644
--- a/core/command_runner.py
+++ b/core/command_runner.py
@@ -298,6 +298,7 @@ async def run_supervised_command(
extra_env: Optional[Mapping[str, str]] = None,
remove_env: Collection[str] = (),
discard_stderr: bool = False,
+ hide_console: bool = False,
) -> SupervisedCommandResult:
"""Run one command under the stable supervisor and return its outcome.
@@ -320,6 +321,11 @@ async def run_supervised_command(
for key in remove_env:
spawn_env.pop(key, None)
spawn_env[watch_worker.PROCESS_IDENTITY_ENV] = worker_marker
+ # A GUI's short metadata probes must hide both the supervisor and its
+ # command on Windows; the worker consumes this private launch instruction.
+ spawn_env.pop(watch_worker.HIDE_CONSOLE_ENV, None)
+ if hide_console:
+ spawn_env[watch_worker.HIDE_CONSOLE_ENV] = "1"
process = await asyncio.create_subprocess_exec(
os.path.abspath(sys.executable),
supervisor_path(),
@@ -328,7 +334,7 @@ async def run_supervised_command(
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=(asyncio.subprocess.DEVNULL if discard_stderr else asyncio.subprocess.PIPE),
- **isolated_subprocess_kwargs(),
+ **isolated_subprocess_kwargs(console=not hide_console),
)
identity = capture_spawned_process_identity(process.pid, worker_marker)
diff --git a/core/watch_worker.py b/core/watch_worker.py
index 9e9e0c398..2c6f714f2 100644
--- a/core/watch_worker.py
+++ b/core/watch_worker.py
@@ -14,6 +14,7 @@ from typing import Any, BinaryIO
import psutil
PROCESS_IDENTITY_ENV = "AVIBE_PROCESS_IDENTITY"
+HIDE_CONSOLE_ENV = "AVIBE_SUPERVISOR_HIDE_CONSOLE"
WATCH_WORKER_PROTOCOL_VERSION = 1
WATCH_WORKER_ERROR_PREFIX = "AVIBE_WATCH_WORKER_ERROR:"
_MAX_SPEC_BYTES = 16 * 1024 * 1024
@@ -280,6 +281,8 @@ def _run_watch_worker() -> int:
command, shell_command = _read_watch_worker_spec()
child_env = dict(os.environ)
child_env.pop(PROCESS_IDENTITY_ENV, None)
+ hide_console = child_env.pop(HIDE_CONSOLE_ENV, None) == "1"
+ creation_options = {"creationflags": subprocess.CREATE_NO_WINDOW} if os.name == "nt" and hide_console else {}
identity_anchor = _start_posix_identity_anchor()
try:
@@ -292,6 +295,7 @@ def _run_watch_worker() -> int:
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
+ **creation_options,
)
except OSError as exc:
raise _CommandSpawnError(exc) from exc
diff --git a/docs/plans/cli-health-detection.md b/docs/plans/cli-health-detection.md
new file mode 100644
index 000000000..6b95d0248
--- /dev/null
+++ b/docs/plans/cli-health-detection.md
@@ -0,0 +1,52 @@
+# CLI health owned by detection (#2257)
+
+## Contract
+
+A native CLI detection observes the selected executable, not merely its directory entry. The observation contains `found`, `path`, `status` (`ok`, `broken`, `missing`, `unknown`), `version`, and a closed safe `reason` code. `found` retains its presence meaning; only `status == ok` certifies runnability. The version belongs to that same successful, bounded `--version` observation. Non-native command discovery (npm, shells, etc.) retains presence semantics and does not impersonate native backend health.
+
+The native backend identity is explicit on the detection request, so custom/draft paths are classified using the right CLI's version contract. Explicit existing paths are tested even when they lack execute permission. A draft is never judged using the saved path. An explicit native path that is missing stays missing: another healthy PATH installation cannot certify it. Bare command discovery still uses the existing resolver. Generic non-backend tool discovery is unchanged.
+
+One detection owner runs probes using the existing supervised command runner, with output limits, timeout and owned-tree teardown. HTTP consumers await it natively; synchronous CLI/installer workers use its synchronous adapter, not a new per-request event-loop bridge. Initial detections/read-backs are uncached: replacing an npm platform package can change health without changing the launcher's stat or version-cache key.
+
+Backend-specific version parsing accepts actual CLI formats, not an arbitrary semver in a crash trace. Nonzero exit, timeout, spawn failure, truncated/invalid output cannot certify health. Raw stdout/stderr is never a card diagnostic. CLI health remains separate from auth, provider/model routing, controller application state and overall entry eligibility. Built-in Vibey is not a CLI backend.
+
+## Consumers
+
+- `/api/cli/detect`: native identity + selected path -> authoritative observation.
+- `/api/backend/<name>/runtime`: optional selected path -> the same observation, plus existing lifecycle/update information. No separate `runnable` verdict.
+- Welcome, AgentDetection, SettingsBackendsPage, useBackendRuntime, BackendLifecycleChip, final onboarding entryGate and CLI doctor consume `status`, not `found`/`installed` as readiness. Native UI detection obtains the runtime projection once and shares that observation with its lifecycle chip; subsequent explicit refreshes carry the selected path and discard stale completions. Human unsaved path edits cannot mutate a different saved installation. Existing connection/source/application gates remain required.
+- Install/upgrade: exit zero is only a candidate success. Fresh native vendor installs use the destinations from the inspected scripts: OpenCode `HOME/.opencode/bin/opencode[.exe]`, Claude `HOME/.local/bin/claude[.exe]`. They do not accept an unrelated same-name CLI discovered elsewhere. Fresh/upgrade Codex npm uses its declared prefix target; app-private desktop validation/activation remains a separate contract. A missing/broken result fails. Existing app-private candidate verification/ownership and install locks remain in force.
+
+## Repair
+
+A healthy CLI keeps its ordinary native update route, but success is bound to the actual executable selected before invocation—even when configured by a bare name. A missing, non-executable or still-broken selected result fails without probing or persisting another installation. An upstream relocation without operation-specific attribution is verification failure, not permission for basename fallback. Codex's pre-existing npm `NPM_CONFIG_PREFIX` policy is an explicitly declared destination on every supported platform: POSIX uses its existing prefix policy, while Windows derives the active prefix with the same npm command/environment and verifies `<prefix>\\codex.cmd`; query failure is an actionable refusal. An existing selected alias is retained only if it names the same artifact at that declared destination. Homebrew Codex updates are accepted only for a stable `<brew-prefix>/bin/codex[.exe]` launcher whose resolved target remains inside that same brew prefix; otherwise the route refuses before upgrade. This is not a general relocation framework. A broken Claude/OpenCode CLI cannot be its own repair tool. Determine supported existing installation provenance without executing that CLI; use its package manager or native bootstrap independently, preserving source and resulting path. Unsupported/ambiguous sources return a safe actionable failure rather than silently migrating the install. App-private desktop installs retain their installer and activation boundary.
+
+### Native OpenCode support/refusal ledger
+
+Only the positively identified canonical `~/.opencode/bin/opencode` installation uses its vendor bootstrap. Its installer environment is a copy with that directory (including equivalent directory entries) removed from PATH. `BASH_ENV`, `ENV`, `SHELLOPTS`, `BASHOPTS` and exported Bash functions are removed from that child environment only. A non-executing `command -v opencode` guard refuses any residual executable alias, wrapper, function or second installation **before network activity**; the same guard prefixes the bootstrap stream in the non-login/non-rc consumer shell. The official installer receives `--no-modify-path`. No shell configuration changes, renamed/deleted old executable, source migration, wrapper inspection, or new native artifact downloader is involved.
+
+A residual resolution conflict is an actionable refusal, not an attempted repair. Even after exit zero, the exact selected destination must pass fresh detection under the **normal launch environment**, not the masked installer environment. Missing target, wrong output and timeout remain failure even if another healthy installation exists. Install-job success carries that validated observation; the restart fingerprint reuses its path/version rather than inventing an independent after-version verdict. Already activated app-private generations are not removed if final read-back fails.
+
+### Supervised probe launch contract
+
+`core.command_runner.run_supervised_command(hide_console=True)` is opt-in. It hides the Windows supervisor and supplies private `AVIBE_SUPERVISOR_HIDE_CONSOLE=1` to `core.watch_worker`, which consumes the instruction, hides the actual Windows command and does not forward the flag to that command. Default callers retain existing console behavior. Shared supervision owns output limits, timeout/cancellation and descendant cleanup. Mocked Win32 flag assertions are not a claim of native Windows acceptance.
+
+Not included: npm residue cleanup, general install-source migration, generic health service, auth/routing rewrites, deployment, unrelated runtime/VM changes. Preserve #2452 startup diagnosis and input retry behavior.
+
+## Producer-to-consumer boundary ledger
+
+| Boundary | Authority and invariant | Regression evidence |
+| --- | --- | --- |
+| Explicit selection | Detection observes that path; missing stays missing without another-install fallback. | HTTP draft/saved separation; explicit and bare upgrade matrices. |
+| Bare selection / presence | Runnable discovery keeps its priority; if none works, existence discovery includes the same supported standard, PATH and npm-global sources without requiring execute permission. | Non-executable custom npm prefix outside standard HOME/PATH remains `found/broken` and repairs its original prefix. |
+| Probe execution | Shared supervised runner and stable existing cwd; backend version shape and normal/private launch environment. | Real valid CLI while the owned service subprocess's old cwd has been deleted; bounded timeout/cancellation and output. |
+| UI path / intent | A request captures its requested path. A missing observation retains that path, not an old render closure. Revision and human-intent guards reject late completions. | Saved-missing initial load, explicit retry, and edit-during-probe tests. |
+| Install/update result | Existing upgrades verify their preselected executable. An explicitly declared Codex npm prefix verifies its own output; an alias survives only if it names that artifact. | Missing/nonexec/broken/same-path success plus old-healthy/new-target-missing npm controls. |
+| Auth/source/application | CLI health is an independent conjunction, not an auth verdict or an application receipt. Built-in backends have no CLI requirement. | Guarded auth harness supplies deterministic command-observation inputs; real HTTP projection refuses broken CLI and recovers at the same selection while other gates can still refuse. |
+| Setup consumption | Wizard forwards the native backend identity; final entry gate consumes health plus the existing independent gates. | Wizard/entry-gate UI tests and cataloged HTTP auth/setup flow; not a claim of the pre-existing partial real-browser-to-real-API journey. |
+
+The first review correction stays within these boundaries. No new cache, source migration, cwd policy, scenario framework or permission model is introduced. CI fixtures follow the actual async producer signatures without relaxing process/host-effect guards. Capability-specific backend relations are classified explicitly rather than excluded from the catalog-universe audit.
+
+## Evidence required
+
+Controlled real subprocesses cover valid backend versions, nonzero Node crash-tail versions, exit-zero wrong output, non-executable/missing paths, bounded output, timeout/descendants, replacements and draft-vs-saved paths. Installer consumers cover false-success read-back, healthy source-preserving update, and broken repair without invoking the damaged CLI. API/UI consumers cover broken state, stale completions and unchanged auth/entry gates. Focused tests, UI build and exact-head review/CI complete the gate; native-platform gaps are reported explicitly.
diff --git a/tests/e2e/json_http_client.py b/tests/e2e/json_http_client.py
index 2d3046a35..74ee58aeb 100644
--- a/tests/e2e/json_http_client.py
+++ b/tests/e2e/json_http_client.py
@@ -22,8 +22,8 @@ class JsonHttpClient:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
+ headers["Origin"] = self.base_url
if method in {"POST", "PUT", "PATCH", "DELETE"}:
- headers["Origin"] = self.base_url
headers["X-Vibe-CSRF-Token"] = self.csrf_token(timeout=timeout)
request = urllib.request.Request(f"{self.base_url}{path}", data=data, headers=headers, method=method)
diff --git a/tests/scenario_harness/auth_setup.py b/tests/scenario_harness/auth_setup.py
index 1fac6cad0..f83a135a3 100644
--- a/tests/scenario_harness/auth_setup.py
+++ b/tests/scenario_harness/auth_setup.py
@@ -1,3 +1,7 @@
+import json
+from pathlib import Path
+
+from core.command_runner import SupervisedCommandResult
from config.v2_config import V2Config
from core.agent_auth_service import AgentAuthService
from tests.scenario_harness.core import BaseScenarioHarness, FakeProcess, ScenarioControllerBase
@@ -16,6 +20,40 @@ def save_direct_auth_config(config: V2Config | None = None) -> V2Config:
return config
+class CliCommandObservations:
+ """Auth scenarios own command responses, not a second health/readiness verdict.
+
+ The real detection parser and HTTP projections consume these responses.
+ Real native processes remain forbidden here; isolated CLI tests own that layer.
+ """
+
+ def __init__(self):
+ self.responses = {}
+ self.calls = []
+
+ def replace(self, path: Path, *, stdout: str, exit_code: int = 0, stderr: str = ""):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ payload = {"stdout": stdout, "exit_code": exit_code, "stderr": stderr}
+ path.write_text(json.dumps(payload), encoding="utf-8")
+ path.chmod(0o755)
+ self.responses[str(path)] = payload
+
+ async def run(self, *, command, label, **_kwargs):
+ assert command[1:] == ["--version"], "Only CLI metadata probes are scenario-controlled"
+ backend = label.split()[0]
+ defaults = {"claude": "2.1.34 (Claude Code)", "codex": "codex-cli 0.162.1", "opencode": "1.2.15"}
+ assert backend in defaults
+ path = command[0]
+ self.calls.append((backend, path))
+ payload = self.responses.get(path, {"stdout": defaults[backend], "exit_code": 0, "stderr": ""})
+ return SupervisedCommandResult(**payload, timed_out=False)
+
+ def bind(self, monkeypatch):
+ from vibe import cli_health
+ monkeypatch.setattr(cli_health, "run_supervised_command", self.run)
+ return self
+
+
class AuthSetupScenarioHarness(BaseScenarioHarness):
"""Native Direct-mode setup; Hub OAuth uses its separate scenario harness."""
@@ -25,5 +63,23 @@ class AuthSetupScenarioHarness(BaseScenarioHarness):
self.controller.config.model_hub = config.model_hub
self.service = AgentAuthService(self.controller)
+ def cli_setup_snapshot(self, client, backend: str, path: str):
+ """The actual HTTP consumers used by native setup, with no UI simulation."""
+ base_url = "http://127.0.0.1"
+ headers = {"Origin": base_url}
+ runtime = client.get(
+ f"/api/backend/{backend}/runtime",
+ params={"cli_path": path},
+ base_url=base_url,
+ headers=headers,
+ )
+ connection = client.get(
+ f"/api/backend/{backend}/connection",
+ base_url=base_url,
+ headers=headers,
+ )
+ assert runtime.status_code == 200 and connection.status_code == 200
+ return runtime.get_json(), connection.get_json()
+
def flow(self, backend: str):
return self.service._flows[f"C1:{backend}"]
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index 051f212dc..d2b5a8c0a 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -580,4 +580,27 @@ scenarios:
supporting_tests:
- ui/src/components/onboarding/entryGate.test.ts
- tests/test_model_hub_vibey_consumer.py
+ - id: AUTH-SETUP-133
+ name: Selected broken native CLI refuses setup eligibility, then recovers at the same path
+ status: covered
+ kind: recovery_path
+ layer: scenario
+ backend: codex
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_selected_cli_health_refusal_recovers_through_setup_http
+ # This is the real HTTP runtime/connection/config boundary with deterministic
+ # command observations supplied by the existing guarded auth_setup harness.
+ # The production health parser and eligibility projection remain real; no
+ # native process, host credential or provider request is permitted here.
+ # Replacement changes an owned test-home fixture at the SAME selected path.
+ # Auth, Hub source supply and application refusal remain required after CLI health recovers.
+ # Supporting UI tests exercise the actual Wizard adapter/final gate using
+ # controlled responses. This does NOT cover the partial assembled real-browser
+ # to real-API journey recorded in AUTH-SETUP-123, nor native platform installs.
+ supporting_tests:
+ - tests/test_cli_health.py
+ - tests/test_cli_repair.py
+ - tests/test_cli_detection_api.py
+ - ui/src/components/onboarding/WizardCompletion.test.tsx
+ - ui/src/components/onboarding/entryGate.test.ts
+ - ui/src/components/settings/shared/useBackendRuntime.test.tsx
next_priority: []
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index c7664db81..240136336 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -52,7 +52,7 @@ from core.handlers.model_hub.service import (
)
from core.show_pages import ShowPageStore
from modules.agents.codex.agent import CodexAgent
-from tests.scenario_harness.auth_setup import AuthSetupScenarioHarness, FakeProcess, save_direct_auth_config
+from tests.scenario_harness.auth_setup import AuthSetupScenarioHarness, CliCommandObservations, FakeProcess, save_direct_auth_config
from tests.scenario_harness.core import ScenarioExpect, ScenarioRunner, ScenarioStep
from tests.ui_server_test_helpers import _save_config, csrf_headers, remote_session_cookie
from storage import remote_access_authorization_service
@@ -102,6 +102,72 @@ def _guard_native_auth_boundaries(monkeypatch, _isolate_vibe_remote_home):
monkeypatch.setattr(asyncio, "create_subprocess_shell", forbidden)
monkeypatch.setattr(psutil, "process_iter", forbidden)
monkeypatch.setattr(native_oauth_store, "_KEYCHAIN_STORE", native_oauth_store._FixtureKeychainStore())
+ # Keep the existing no-process guard. Supply command evidence only at the
+ # shared probe transport seam; production parsing/readiness remain real.
+ CliCommandObservations().bind(monkeypatch)
+
+
+def test_selected_cli_health_refusal_recovers_through_setup_http(monkeypatch, tmp_path):
+ """AUTH-SETUP-133: deterministic command boundary -> real HTTP setup projection.
+
+ UI Wizard/final-admission consumption is covered separately; this does not
+ claim the partial AUTH-SETUP-123 real-browser-to-real-API journey.
+ """
+ from vibe import api, internal_client
+
+ selected = tmp_path / "selected CLI" / "codex"
+ commands = CliCommandObservations().bind(monkeypatch)
+ commands.replace(selected, stdout="", exit_code=1, stderr="Missing dependency\nNode.js v22.18.0")
+ config = V2Config.default()
+ config.agents.codex.enabled = True
+ config.agents.codex.cli_path = str(selected)
+ save_direct_auth_config(config)
+ harness = AuthSetupScenarioHarness()
+ client = app.test_client()
+ auth = {"key": "fixture-only-key"}
+ application = {"state": "applied"}
+ monkeypatch.setattr(api, "get_codex_auth", lambda: {"ok": True, "active_auth_mode": "api_key" if auth["key"] else "none"})
+ async def applied(*_args, **_kwargs):
+ return {"status_code": 200, "body": {"ok": True, "state": application["state"], "controller_pid": 123}}
+ monkeypatch.setattr(internal_client, "backend_application", applied)
+ monkeypatch.setattr(api, "_backend_apply_receipts", {})
+ monkeypatch.setattr(api, "_cached_latest", lambda _name: None)
+ monkeypatch.setattr(api, "_codex_process_status", lambda _path: "stopped")
+ runner = ScenarioRunner(harness)
+ def refused(_h):
+ runtime, connection = harness.cli_setup_snapshot(client, "codex", str(selected))
+ assert runtime["installed"] and runtime["status"] == "broken" and runtime["current_version"] is None
+ assert connection["cli_status"] == "broken" and not connection["entry_eligible"]
+ assert V2Config.load().agents.codex.cli_path == str(selected)
+ assert not V2Config.load().setup_completed
+ def replace(_h):
+ commands.replace(selected, stdout="codex-cli 0.162.1")
+ def recovered(_h):
+ runtime, connection = harness.cli_setup_snapshot(client, "codex", str(selected))
+ assert runtime["status"] == "ok" and runtime["resolved_path"] == str(selected)
+ assert connection["entry_eligible"] and connection["auth"] == "api_key"
+ auth["key"] = None
+ assert not harness.cli_setup_snapshot(client, "codex", str(selected))[1]["entry_eligible"]
+ auth["key"] = "fixture-only-key"
+ application["state"] = "draining"
+ assert not harness.cli_setup_snapshot(client, "codex", str(selected))[1]["entry_eligible"]
+ application["state"] = "applied"
+ assert harness.cli_setup_snapshot(client, "codex", str(selected))[1]["entry_eligible"]
+ hub = V2Config.load()
+ hub.model_hub.agents["codex"].mode = "hub"
+ hub.model_hub.sources = []
+ hub.save()
+ source_blocked = harness.cli_setup_snapshot(client, "codex", str(selected))[1]
+ assert source_blocked["supply_mode"] == "hub" and not source_blocked["entry_eligible"]
+ save_direct_auth_config()
+ assert harness.cli_setup_snapshot(client, "codex", str(selected))[1]["entry_eligible"]
+ def complete(_h):
+ response = client.post("/api/config", json={"setup_completed": True}, headers=csrf_headers(client))
+ assert response.status_code == 200 and V2Config.load().setup_completed
+ assert V2Config.load().agents.codex.cli_path == str(selected)
+ asyncio.run(runner.run(ScenarioStep("refuse", refused), ScenarioStep("replace", replace), ScenarioStep("reobserve-and-gates", recovered), ScenarioStep("complete", complete)))
+ ScenarioExpect.step_history(runner, ["refuse", "replace", "reobserve-and-gates", "complete"])
+ assert commands.calls and {path for _backend, path in commands.calls} == {str(selected)}
def test_auth_setup_catalog_priorities_reference_live_scenarios():
diff --git a/tests/test_backend_connection.py b/tests/test_backend_connection.py
index d1eb7aef9..80642fd67 100644
--- a/tests/test_backend_connection.py
+++ b/tests/test_backend_connection.py
@@ -50,6 +50,15 @@ def native_safety(monkeypatch, _isolate_vibe_remote_home):
):
monkeypatch.delenv(name, raising=False)
monkeypatch.setattr(native_oauth_store, "_KEYCHAIN_STORE", native_oauth_store._FixtureKeychainStore())
+ # These tests isolate credential/application ownership. Native CLI execution
+ # is forbidden here; the detection owner supplies its independent evidence.
+ def observation(binary, backend=None):
+ path = api.resolve_cli_path(binary)
+ return api.CliHealth(bool(path), path, "ok" if path else "missing", "1.0.0" if path else None).payload()
+ async def async_observation(binary, backend=None):
+ return observation(binary, backend)
+ monkeypatch.setattr(api, "detect_cli", observation)
+ monkeypatch.setattr(api, "detect_cli_async", async_observation)
@pytest.fixture
@@ -73,6 +82,16 @@ def connection(monkeypatch, tmp_path):
return SimpleNamespace(config=config, probe=probe, claude_auth_read=claude_auth_read)
[email protected]("backend", ["claude", "codex", "opencode"])
+def test_broken_cli_is_present_but_cannot_admit_even_with_applied_configuration(connection, monkeypatch, backend):
+ monkeypatch.setattr(api, "detect_cli_async", AsyncMock(return_value=api.CliHealth(True, "/fixture/broken", "broken", reason="probe_failed").payload()))
+ observed = asyncio.run(api.get_backend_connection(backend))
+ assert observed["installed"] is True and observed["cli_status"] == "broken"
+ assert observed["application"] == "applied"
+ assert not observed["ready"] and not observed["entry_eligible"]
+ assert observed["auth"] == "unknown" # not mislabeled as a credential rejection
+
+
@pytest.mark.parametrize("state,ready", [("applied", True), ("draining", False), ("failed", False), ("unavailable", False)])
def test_application_is_consumed_instead_of_acceptance(connection, state, ready):
connection.probe.return_value["body"]["state"] = state
@@ -167,7 +186,6 @@ def test_install_job_applies_persisted_path_before_admitting_connection(monkeypa
assert not V2Config.load().load_warnings
installed_path = str(tmp_path / "安装 后端/bin" / backend)
monkeypatch.setattr(api, "resolve_cli_path", lambda _: installed_path)
- monkeypatch.setattr(api, "_probe_cli_version", lambda _: "1.0.0")
monkeypatch.setattr(api.subprocess, "Popen", lambda *a, **kw: SimpleNamespace(
communicate=lambda **_: ("fixture installed", ""), returncode=0,
))
diff --git a/tests/test_backend_registration_contract.py b/tests/test_backend_registration_contract.py
index 2139f1498..d0be908eb 100644
--- a/tests/test_backend_registration_contract.py
+++ b/tests/test_backend_registration_contract.py
@@ -65,6 +65,8 @@ PYTHON_DECLARATIONS = {
("vibe/backend_model_catalog.py", "Set", frozenset({"claude", "codex"})): (1, "native_subset", "Backends with bundled model catalogs."),
("vibe/cli.py", "Tuple", frozenset({"claude", "codex"})): (1, "native_subset", "Native-only model picker refresh."),
("vibe/desktop_backends.py", "Dict", NATIVE): (1, "native", "CLI package install specifications."),
+ ("vibe/cli_health.py", "Dict", NATIVE): (1, "native", "Backend-specific native CLI version grammars, not another Agent universe."),
+ ("vibe/cli_repair.py", "Dict", NATIVE): (2, "native", "npm package and Homebrew formula coordinates for source-preserving native CLI repair."),
("vibe/global_agents_md.py", "Dict", NATIVE): (1, "native", "Native global instruction filenames."),
("vibe/model_hub_runtime/adapter.py", "Dict", frozenset({"claude", "codex"})): (1, "native_subset", "Native subscription vendors."),
("vibe/model_hub_runtime/state.py", "Dict", frozenset({"claude", "codex"})): (1, "native_subset", "Vendor aliases, including provider names."),
diff --git a/tests/test_cli_detection_api.py b/tests/test_cli_detection_api.py
new file mode 100644
index 000000000..505be8e0e
--- /dev/null
+++ b/tests/test_cli_detection_api.py
@@ -0,0 +1,353 @@
+"""Real detection evidence reaches HTTP and lifecycle consumers, without credentials."""
+
+import asyncio
+import json
+import os
+import sys
+from pathlib import Path
+from unittest.mock import AsyncMock
+
+import pytest
+
+from config.v2_config import V2Config
+from tests.e2e.json_http_client import JsonHttpClient
+from tests.test_cli_health import make_cli, fixture_env
+from vibe import api, ui_server
+
+
+def cli_api(tmp_path, monkeypatch):
+ env = fixture_env(tmp_path)
+ monkeypatch.setattr(api, "_command_env_for", lambda _path: dict(env))
+ monkeypatch.setattr(api, "_cached_latest", lambda _name: "0.163.0")
+ monkeypatch.setattr(api, "_codex_process_status", lambda _path: "stopped")
+ config = V2Config.default()
+ config.agents.codex.enabled = True
+ config.agents.codex.cli_path = "saved-codex"
+ config.save()
+ return ui_server.app.test_client(), env
+
+
+def test_draft_runtime_probes_the_selected_cli_and_does_not_save_it(cli_api, tmp_path):
+ client, _ = cli_api
+ cli = make_cli(tmp_path, 'print("codex-cli 0.162.1")\n')
+ response = client.get(
+ "/api/backend/codex/runtime",
+ params={"cli_path": str(cli)},
+ headers={"Origin": "http://127.0.0.1:15131"},
+ base_url="http://127.0.0.1:15131",
+ )
+ assert response.status_code == 200, response.get_json()
+ body = response.get_json()
+ assert body["status"] == "ok" and body["current_version"] == "0.162.1"
+ assert body["cli_path"] == str(cli) and body["resolved_path"] == str(cli)
+ assert V2Config.load().agents.codex.cli_path == "saved-codex"
+ assert response.headers["Cache-Control"] == "private, no-store"
+
+
+def test_crash_version_is_broken_through_both_http_consumers(cli_api, tmp_path):
+ client, _ = cli_api
+ cli = make_cli(
+ tmp_path,
+ 'import sys\nprint("Error: missing platform package; PRIVATE_SENTINEL; Node.js v22.18.0",file=sys.stderr)\nsys.exit(1)\n',
+ )
+ detection_response = client.get(
+ "/api/cli/detect",
+ params={"binary": str(cli), "backend": "codex"},
+ headers={"Origin": "http://127.0.0.1:15131"},
+ base_url="http://127.0.0.1:15131",
+ )
+ assert detection_response.status_code == 200, detection_response.get_json()
+ detection = detection_response.get_json()
+ runtime_response = client.get(
+ "/api/backend/codex/runtime",
+ params={"cli_path": str(cli)},
+ headers={"Origin": "http://127.0.0.1:15131"},
+ base_url="http://127.0.0.1:15131",
+ )
+ assert runtime_response.status_code == 200, runtime_response.get_json()
+ runtime = runtime_response.get_json()
+ assert detection["found"] and detection["status"] == "broken" and detection["version"] is None
+ assert runtime["installed"] and runtime["status"] == "broken" and runtime["current_version"] is None
+ assert not runtime["has_update"]
+ assert "PRIVATE_SENTINEL" not in str(detection) + str(runtime)
+
+
+def test_missing_selected_path_never_substitutes_another_installation(cli_api, tmp_path, monkeypatch):
+ missing = str(tmp_path / "missing/codex")
+ monkeypatch.setattr(
+ api, "resolve_cli_path", lambda _: pytest.fail("an explicit missing selection must not discover another CLI")
+ )
+ assert api.detect_cli(missing, "codex")["status"] == "missing"
+
+
+ "headers",
+ [{}, {"Origin": "http://evil.example"}],
+ ids=["missing-origin", "foreign-origin"],
+)
+def test_cli_detect_requires_same_origin_browser_evidence_before_probe(cli_api, monkeypatch, headers):
+ client, _ = cli_api
+ probe = AsyncMock(side_effect=AssertionError("rejected request must not execute a probe"))
+ monkeypatch.setattr(api, "detect_cli_async", probe)
+
+ response = client.get(
+ "/api/cli/detect",
+ params={"binary": "/fixture/selected", "backend": "codex"},
+ headers=headers,
+ base_url="http://127.0.0.1:15131",
+ )
+
+ assert response.status_code == 403, response.get_json()
+ assert response.get_json()["error"] == "same_origin_required"
+ probe.assert_not_called()
+
+
+def test_cli_detect_allows_same_origin_browser_probe(cli_api, tmp_path):
+ client, _ = cli_api
+ cli = make_cli(tmp_path, 'print("codex-cli 0.162.1")\n')
+
+ response = client.get(
+ "/api/cli/detect",
+ params={"binary": str(cli), "backend": "codex"},
+ headers={"Origin": "http://127.0.0.1:15131"},
+ base_url="http://127.0.0.1:15131",
+ )
+
+ assert response.status_code == 200, response.get_json()
+ assert response.get_json()["status"] == "ok"
+
+
+def test_cli_detect_allows_same_origin_setup_host_browser_probe(cli_api, tmp_path):
+ client, _ = cli_api
+ config = V2Config.load()
+ config.ui.setup_host = "192.168.2.3"
+ config.remote_access.vibe_cloud.enabled = False
+ config.save()
+ cli = make_cli(tmp_path, 'print("codex-cli 0.162.1")\n')
+
+ response = client.get(
+ "/api/cli/detect",
+ params={"binary": str(cli), "backend": "codex"},
+ headers={"Origin": "http://192.168.2.3:15131"},
+ base_url="http://192.168.2.3:15131",
+ )
+
+ assert response.status_code == 200, response.get_json()
+ assert response.get_json()["status"] == "ok"
+
+
+def test_backend_runtime_allows_same_origin_setup_host_browser_probe(cli_api, tmp_path):
+ client, _ = cli_api
+ config = V2Config.load()
+ config.ui.setup_host = "192.168.2.3"
+ config.remote_access.vibe_cloud.enabled = False
+ config.save()
+ cli = make_cli(tmp_path, 'print("codex-cli 0.162.1")\n')
+
+ response = client.get(
+ "/api/backend/codex/runtime",
+ params={"cli_path": str(cli)},
+ headers={"Origin": "http://192.168.2.3:15131"},
+ base_url="http://192.168.2.3:15131",
+ )
+
+ assert response.status_code == 200, response.get_json()
+ assert response.get_json()["status"] == "ok"
+
+
+ "headers",
+ [{}, {"Origin": "http://evil.example"}],
+ ids=["missing-origin", "foreign-origin"],
+)
+def test_backend_runtime_requires_same_origin_browser_evidence_before_probe(cli_api, monkeypatch, headers):
+ client, _ = cli_api
+ runtime = AsyncMock(side_effect=AssertionError("rejected request must not execute a probe"))
+ monkeypatch.setattr(api, "get_backend_runtime_async", runtime)
+
+ response = client.get(
+ "/api/backend/codex/runtime",
+ params={"cli_path": "/fixture/selected"},
+ headers=headers,
+ base_url="http://127.0.0.1:15131",
+ )
+
+ assert response.status_code == 403, response.get_json()
+ assert response.get_json()["error"] == "same_origin_required"
+ runtime.assert_not_awaited()
+
+
+def test_e2e_json_http_client_sends_origin_on_get(monkeypatch):
+ client = JsonHttpClient("http://127.0.0.1:15123")
+ captured = {}
+
+ class Response:
+ status = 200
+
+ @staticmethod
+ def read():
+ return b'{"found": true}'
+
+ def open_request(request, *, timeout):
+ captured["request"] = request
+ captured["timeout"] = timeout
+ return Response()
+
+ monkeypatch.setattr(client.opener, "open", open_request)
+
+ status, payload = client.get_json("/api/cli/detect?binary=python3")
+
+ assert status == 200
+ assert payload == {"found": True}
+ assert captured["request"].get_method() == "GET"
+ assert captured["request"].get_header("Origin") == client.base_url
+
+
+ "route,query",
+ [
+ ("/api/cli/detect", {"binary": "/fixture/selected", "backend": "codex"}),
+ ("/api/backend/codex/runtime", {"cli_path": "/fixture/selected"}),
+ ],
+)
+def test_management_authority_is_checked_before_custom_path_probe(cli_api, monkeypatch, route, query):
+ client, _ = cli_api
+ probe = AsyncMock(side_effect=AssertionError("unauthorized request must not execute a probe"))
+ monkeypatch.setattr(api, "detect_cli_async", probe)
+ response = client.get(route, params=query, environ_base={"REMOTE_ADDR": "203.0.113.44"})
+ assert response.status_code in {401, 403, 503}, response.get_json()
+ probe.assert_not_called()
+
+
+def test_invalid_backend_does_not_execute_custom_path(cli_api, monkeypatch):
+ client, _ = cli_api
+ probe = AsyncMock(side_effect=AssertionError("invalid backend must not probe"))
+ monkeypatch.setattr(api, "probe_cli", probe)
+ response = client.get("/api/cli/detect", params={"binary": "/fixture/selected", "backend": "vibey"})
+ assert response.status_code == 400
+ probe.assert_not_called()
+
+
[email protected](os.name == "nt", reason="Windows cannot remove a process working directory")
+def test_health_and_runtime_http_survive_an_owned_removed_cwd(tmp_path):
+ import subprocess
+ import sys
+
+ cli = make_cli(tmp_path, 'print("codex-cli 0.162.1")\n')
+ env = fixture_env(tmp_path)
+ env["PYTHONPATH"] = str(Path(__file__).resolve().parents[1])
+ driver = tmp_path / "removed_cwd_driver.py"
+ driver.write_text(
+ """import asyncio,json,os
+from pathlib import Path
+from config.v2_config import V2Config
+from vibe import api,ui_server
+from vibe.cli_health import probe_cli
+config=V2Config.default();config.agents.codex.cli_path=CLI;config.save()
+api._cached_latest=lambda _name: None
+api._codex_process_status=lambda _path: 'stopped'
+client=ui_server.app.test_client()
+gone=Path(GONE);gone.mkdir();os.chdir(gone);gone.rmdir()
+try:os.getcwd();raise AssertionError('cwd was not removed')
+except FileNotFoundError:pass
+health=asyncio.run(probe_cli('codex',CLI,env=dict(os.environ)))
+response=client.get('/api/backend/codex/runtime',params={'cli_path':CLI},headers={'Origin':'http://127.0.0.1:15131'},base_url='http://127.0.0.1:15131')
+body=response.get_json()
+assert health.status=='ok' and health.version=='0.162.1'
+assert response.status_code==200 and body['status']=='ok' and body['current_version']=='0.162.1',body
+print(json.dumps({'probe':health.status,'runtime':body['status'],'version':body['current_version']}))
+""".replace("CLI", repr(str(cli))).replace("GONE", repr(str(tmp_path / "removed-service-cwd")))
+ )
+ result = subprocess.run(
+ [sys.executable, str(driver)], cwd=tmp_path, env=env, capture_output=True, text=True, timeout=25
+ )
+ assert result.returncode == 0, result.stderr
+ assert json.loads(result.stdout.strip().splitlines()[-1]) == {"probe": "ok", "runtime": "ok", "version": "0.162.1"}
+
+
+ "backend,target_rel,version",
+ [
+ ("opencode", Path(".opencode/bin/opencode"), "1.2.15"),
+ ("claude", Path(".local/bin/claude"), "2.1.34 (Claude Code)"),
+ ],
+)
[email protected]("write_target", [False, True])
+def test_fresh_vendor_install_reads_only_the_script_destination(
+ tmp_path, monkeypatch, backend, target_rel, version, write_target
+):
+ home = tmp_path / "vendor home"
+ env = fixture_env(tmp_path)
+ env["HOME"] = str(home)
+ script = tmp_path / "controlled-vendor-installer.py"
+ target = home / target_rel
+ target_body = "#!" + sys.executable + "\nprint(" + repr(version) + ")\n"
+ script.write_text(
+ "from pathlib import Path\n"
+ + (
+ f"p=Path({str(target)!r});p.parent.mkdir(parents=True,exist_ok=True);p.write_text({target_body!r});p.chmod(0o755)\n"
+ if write_target
+ else ""
+ )
+ + "print('installer-exit-zero')\n",
+ encoding="utf-8",
+ )
+ target_script = [sys.executable, str(script)]
+ monkeypatch.setattr(Path, "home", lambda: home)
+ monkeypatch.setattr(api.Path, "home", lambda: home)
+ monkeypatch.setenv("PATH", str(tmp_path / "empty-bin"))
+ monkeypatch.setattr(api, "_command_env_for", lambda _path: dict(env))
+ monkeypatch.setattr(api, "_configured_agent_cli_path", lambda _name: backend)
+ monkeypatch.setattr(api, "_candidate_cli_paths", lambda *_args, **_kwargs: [])
+ monkeypatch.setattr(api, "is_desktop_managed_runtime", lambda: False)
+ monkeypatch.setattr(api, "_persist_agent_cli_path", lambda _name, path: persisted.append(path))
+ monkeypatch.setattr(
+ api, "resolve_cli_path", lambda name, **_kwargs: "/usr/bin/" + name if name in {"curl", "bash"} else None
+ )
+ monkeypatch.setattr(api, "_curl_installer_command", lambda _url, _consumer: target_script)
+ persisted = []
+ result = api.install_agent(backend)
+ if write_target:
+ assert result["ok"] and result["path"] == str(target) and persisted == [str(target)]
+ else:
+ assert not result["ok"] and result["code"] == "cli_readback_failed" and persisted == []
+ assert not target.exists()
+
+
+def test_install_job_rejects_success_without_readback(monkeypatch):
+ import time
+
+ monkeypatch.setattr(api, "_agent_runtime_fingerprint", lambda *_args: None)
+ monkeypatch.setattr(api, "install_agent", lambda _name: {"ok": True, "path": "/fixture/cli"})
+ monkeypatch.setattr(
+ api, "restart_backend", lambda *_args, **_kwargs: pytest.fail("unverified install must not refresh")
+ )
+ monkeypatch.setattr(api, "_AGENT_INSTALL_JOBS", {})
+ monkeypatch.setattr(api, "_AGENT_INSTALL_LATEST_BY_BACKEND", {})
+ started = api.start_agent_install_job("codex")
+ deadline = time.monotonic() + 3
+ while time.monotonic() < deadline:
+ result = api.get_agent_install_job(started["job_id"])
+ if result["status"] != "running":
+ break
+ time.sleep(0.01)
+ assert result["status"] == "failed" and result["code"] == "cli_readback_failed"
+
+
+def test_private_publication_is_not_rolled_back_when_final_probe_fails(tmp_path, monkeypatch):
+ from types import SimpleNamespace
+
+ active = tmp_path / "active-native"
+ active.write_bytes(b"published generation")
+ monkeypatch.setattr(
+ api,
+ "install_desktop_backend",
+ lambda *_args, **_kwargs: SimpleNamespace(path=str(active), version="0.162.1", output=None),
+ )
+ monkeypatch.setattr(
+ api, "detect_cli", lambda *_args: api.CliHealth(True, str(active), "broken", reason="probe_failed").payload()
+ )
+ result = api._run_desktop_backend_install("codex", lambda x: x)
+ assert not result["ok"] and result["code"] == "cli_readback_failed"
+ assert active.read_bytes() == b"published generation"
diff --git a/tests/test_cli_health.py b/tests/test_cli_health.py
new file mode 100644
index 000000000..8287564d1
--- /dev/null
+++ b/tests/test_cli_health.py
@@ -0,0 +1,203 @@
+"""Executable evidence, including real supervisor/child boundaries (#2257)."""
+
+import asyncio
+import json
+import os
+import sys
+from pathlib import Path
+
+import pytest
+
+from vibe.cli_health import cli_version, probe_cli
+
+
+ "backend,output,version",
+ [
+ ("claude", "2.1.34 (Claude Code)\n", "2.1.34"),
+ ("claude", "Claude Code 2.1.34", "2.1.34"),
+ ("codex", "codex-cli 0.162.1", "0.162.1"),
+ ("codex", "codex-cli 0.162.1-alpha.2+build.4", "0.162.1-alpha.2+build.4"),
+ ("codex", "codex-cli 0.77.1 (build test)", "0.77.1"),
+ ("opencode", "1.2.15\n", "1.2.15"),
+ ("opencode", "opencode 1.2.15", "1.2.15"),
+ ("opencode", "0.0.0-dev-20261011", "0.0.0-dev-20261011"),
+ ("opencode", "local", "local"),
+ ],
+)
+def test_cli_version_shapes(backend, output, version):
+ assert cli_version(backend, output, "a harmless stderr warning") == version
+ assert cli_version(backend, "", output) == version
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+ "output",
+ [
+ "Error: Missing optional dependency @openai/codex-darwin-arm64\nNode.js v22.18.0",
+ "Node.js v22.18.0",
+ "v22.18.0",
+ "",
+ "Python 3.12.0",
+ "arbitrary diagnostic 1.2.3",
+ ],
+)
+def test_version_does_not_extract_an_unrelated_semver(backend, output):
+ assert cli_version(backend, output, "") is None
+
+
+def make_cli(tmp_path: Path, body: str) -> Path:
+ script = tmp_path / "CLI 空格.py"
+ script.write_text(body, encoding="utf-8")
+ if os.name == "nt":
+ launcher = tmp_path / "CLI 空格.cmd"
+ launcher.write_text(f'@"{sys.executable}" "{script}" %*\r\n', encoding="utf-8")
+ else:
+ launcher = tmp_path / "CLI 空格"
+ launcher.write_text(f"#!{sys.executable}\n" + body, encoding="utf-8")
+ launcher.chmod(0o755)
+ return launcher
+
+
+def fixture_env(tmp_path):
+ env = {
+ key: value
+ for key, value in os.environ.items()
+ if key
+ in {
+ "PATH",
+ "SYSTEMROOT",
+ "WINDIR",
+ "COMSPEC",
+ "PATHEXT",
+ "PYTHONPATH",
+ "TMPDIR",
+ "TEMP",
+ "TMP",
+ "LANG",
+ "LC_ALL",
+ }
+ or key.startswith(("AVIBE_TEST_", "VIBE_TEST_"))
+ }
+ for key in (
+ "HOME",
+ "AVIBE_HOME",
+ "CODEX_HOME",
+ "CLAUDE_CONFIG_DIR",
+ "XDG_CONFIG_HOME",
+ "XDG_DATA_HOME",
+ "XDG_CACHE_HOME",
+ ):
+ path = tmp_path / key.lower()
+ path.mkdir(exist_ok=True)
+ env[key] = str(path)
+ env.pop("AVIBE_DESKTOP_RUNTIME_ROOT", None)
+ env.pop("AVIBE_DESKTOP_MANAGED_RUNTIME", None)
+ return env
+
+
+ "code,stdout,stderr,status,version",
+ [
+ (0, "codex-cli 0.162.1", "", "ok", "0.162.1"),
+ (1, "", "Error: missing platform package\nNode.js v22.18.0 SECRET_SENTINEL", "broken", None),
+ (1, "codex-cli 0.162.1", "SECRET_SENTINEL", "broken", None),
+ (0, "Node.js v22.18.0", "", "broken", None),
+ (0, "", "", "broken", None),
+ ],
+)
+def test_real_cli_probe_exit_status_and_safe_result(tmp_path, code, stdout, stderr, status, version, caplog):
+ executable = make_cli(
+ tmp_path, f"import sys\nprint({stdout!r})\nprint({stderr!r}, file=sys.stderr)\nsys.exit({code})\n"
+ )
+ health = asyncio.run(probe_cli("codex", str(executable), env=fixture_env(tmp_path)))
+ assert health.status == status and health.version == version
+ assert health.found and health.path == str(executable)
+ assert "SECRET_SENTINEL" not in json.dumps(health.payload()) + caplog.text
+
+
+def test_probe_does_not_cache_unchanged_launcher_metadata(tmp_path):
+ dependency = tmp_path / "dependency"
+ executable = make_cli(
+ tmp_path,
+ f'import pathlib\nprint("codex-cli 0.162.1" if pathlib.Path({str(dependency)!r}).exists() else "Node.js v22.18.0")\n',
+ )
+ before = executable.stat()
+ env = fixture_env(tmp_path)
+ assert asyncio.run(probe_cli("codex", str(executable), env=env)).status == "broken"
+ dependency.touch()
+ assert asyncio.run(probe_cli("codex", str(executable), env=env)).status == "ok"
+ assert (executable.stat().st_mtime_ns, executable.stat().st_size) == (before.st_mtime_ns, before.st_size)
+
+
+def test_probe_timeout_and_output_cap(tmp_path):
+ executable = make_cli(tmp_path, 'import time\nprint("codex-cli 0.162.1", flush=True)\ntime.sleep(60)\n')
+ health = asyncio.run(probe_cli("codex", str(executable), env=fixture_env(tmp_path), timeout_seconds=0.5))
+ assert health.status == "broken" and health.reason == "probe_timeout" and health.version is None
+ executable = make_cli(tmp_path, 'print("codex-cli 0.162.1" + " " * 100_000)\n')
+ health = asyncio.run(probe_cli("codex", str(executable), env=fixture_env(tmp_path)))
+ assert health.status == "broken" and health.reason == "invalid_version"
+
+
[email protected](os.name == "nt", reason="POSIX execute permission")
+def test_non_executable_present_cli_is_not_healthy(tmp_path):
+ executable = make_cli(tmp_path, 'print("codex-cli 0.162.1")\n')
+ executable.chmod(0o644)
+ health = asyncio.run(probe_cli("codex", str(executable), env=fixture_env(tmp_path)))
+ assert health.found and health.status == "broken" and health.version is None
+
+
[email protected](os.name == "nt", reason="POSIX descendant liveness; Windows Job Object covered by runner suite")
[email protected]("cancel", [False, True])
+def test_probe_owns_descendants_on_timeout_and_cancellation(tmp_path, cancel):
+ import psutil
+
+ pid_file = tmp_path / "child.pid"
+ child_code = "import time; time.sleep(60)"
+ executable = make_cli(
+ tmp_path,
+ f'import subprocess,sys,time\nfrom pathlib import Path\np=subprocess.Popen([sys.executable,"-c",{child_code!r}])\nPath({str(pid_file)!r}).write_text(str(p.pid))\nprint("codex-cli 0.162.1",flush=True)\n',
+ )
+
+ async def run():
+ task = asyncio.create_task(
+ probe_cli("codex", str(executable), env=fixture_env(tmp_path), timeout_seconds=60 if cancel else 2)
+ )
+ if cancel:
+ for _ in range(100):
+ if pid_file.exists():
+ break
+ await asyncio.sleep(0.03)
+ assert pid_file.exists(), "owned CLI never started"
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ else:
+ result = await task
+ assert result.status == "broken" and result.reason == "probe_timeout"
+
+ asyncio.run(run())
+ assert pid_file.exists()
+ try:
+ child = psutil.Process(int(pid_file.read_text()))
+ assert not child.is_running() or child.status() == psutil.STATUS_ZOMBIE
+ except psutil.NoSuchProcess:
+ pass
+
+
+def test_probe_uses_private_backend_environment_supplier(tmp_path, monkeypatch):
+ from vibe import desktop_backends
+
+ executable = make_cli(
+ tmp_path,
+ 'import os\nprint("codex-cli 0.162.1" if os.environ.get("OWNED_PRIVATE_HELPER") == "yes" else "missing helper")\n',
+ )
+ supplied = []
+
+ def environment(backend, path, base):
+ supplied.append((backend, path))
+ return {**base, "OWNED_PRIVATE_HELPER": "yes"}
+
+ monkeypatch.setattr(desktop_backends, "desktop_backend_subprocess_environment", environment)
+ health = asyncio.run(probe_cli("codex", str(executable), env=fixture_env(tmp_path)))
+ assert health.status == "ok" and supplied == [("codex", str(executable))]
diff --git a/tests/test_cli_health_launch.py b/tests/test_cli_health_launch.py
new file mode 100644
index 000000000..24e991904
--- /dev/null
+++ b/tests/test_cli_health_launch.py
@@ -0,0 +1,88 @@
+"""The metadata probe's opt-in Windows console policy reaches both processes."""
+
+import asyncio
+import io
+import os
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+from core import command_runner, watch_worker
+
+
[email protected]("hidden", [False, True])
+def test_supervisor_console_policy_is_opt_in_and_not_leaked(tmp_path, monkeypatch, hidden):
+ seen = []
+ original = command_runner.isolated_subprocess_kwargs
+
+ def options(*, console=True):
+ seen.append(console)
+ return original(console=console)
+
+ monkeypatch.setattr(command_runner, "isolated_subprocess_kwargs", options)
+ result = asyncio.run(
+ command_runner.run_supervised_command(
+ command=[
+ sys.executable,
+ "-c",
+ f'import os; print(os.environ.get({watch_worker.HIDE_CONSOLE_ENV!r}, "consumed"))',
+ ],
+ cwd=str(tmp_path),
+ timeout_seconds=5,
+ label="owned console contract",
+ hide_console=hidden,
+ max_output_bytes=1024,
+ env={
+ key: value
+ for key, value in os.environ.items()
+ if key
+ in {
+ "PATH",
+ "SYSTEMROOT",
+ "WINDIR",
+ "COMSPEC",
+ "PATHEXT",
+ "TMPDIR",
+ "TEMP",
+ "TMP",
+ "HOME",
+ "AVIBE_HOME",
+ "CODEX_HOME",
+ "CLAUDE_CONFIG_DIR",
+ "XDG_CONFIG_HOME",
+ "XDG_DATA_HOME",
+ "XDG_CACHE_HOME",
+ "XDG_STATE_HOME",
+ }
+ },
+ )
+ )
+ assert result.exit_code == 0 and result.stdout.strip() == "consumed"
+ assert seen == [not hidden]
+
+
[email protected]("hidden", [False, True])
+def test_windows_worker_hides_actual_child_only_when_requested(monkeypatch, hidden):
+ env = {watch_worker.PROCESS_IDENTITY_ENV: "owned-fixture-marker", "KEEP": "retained"}
+ if hidden:
+ env[watch_worker.HIDE_CONSOLE_ENV] = "1"
+ monkeypatch.setattr(watch_worker, "os", SimpleNamespace(name="nt", environ=env))
+ monkeypatch.setattr(watch_worker, "_install_posix_supervisor_signal_handlers", lambda: None)
+ monkeypatch.setattr(watch_worker, "_install_windows_kill_on_close_job", lambda: object())
+ monkeypatch.setattr(watch_worker, "_read_watch_worker_spec", lambda: (["fixture-cli", "--version"], None))
+ monkeypatch.setattr(watch_worker, "_start_posix_identity_anchor", lambda: None)
+ monkeypatch.setattr(watch_worker, "_stop_posix_identity_anchor", lambda _: None)
+ monkeypatch.setattr(watch_worker, "_wait_for_posix_process_group_exit", lambda *_args, **_kwargs: None)
+ calls = []
+
+ def spawn(command, **kwargs):
+ calls.append((command, kwargs))
+ return SimpleNamespace(stdout=io.BytesIO(), stderr=io.BytesIO(), wait=lambda: 0)
+
+ monkeypatch.setattr(
+ watch_worker, "subprocess", SimpleNamespace(Popen=spawn, PIPE=-1, DEVNULL=-3, CREATE_NO_WINDOW=0x08000000)
+ )
+ assert watch_worker._run_watch_worker() == 0
+ assert calls[0][1]["env"] == {"KEEP": "retained"}
+ assert calls[0][1].get("creationflags", 0) == (0x08000000 if hidden else 0)
diff --git a/tests/test_cli_repair.py b/tests/test_cli_repair.py
new file mode 100644
index 000000000..265100a60
--- /dev/null
+++ b/tests/test_cli_repair.py
@@ -0,0 +1,774 @@
+"""Real child-shell repair boundaries; no user CLI/package manager is changed."""
+
+import asyncio
+import json
+import os
+import shlex
+import subprocess
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from vibe import api, cli_paths
+from tests.test_cli_health import fixture_env
+from vibe.cli_health import cli_version, probe_cli
+from vibe.cli_repair import identify_repair_source, native_bootstrap_env
+
+
+def executable(path, body):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(f"#!{sys.executable}\n" + body, encoding="utf-8")
+ path.chmod(0o755)
+ return path
+
+
+def native_case(tmp_path, monkeypatch):
+ if os.name == "nt":
+ pytest.skip("the vendor native OpenCode installer is POSIX")
+ home = tmp_path / "用户 HOME"
+ home.mkdir()
+ target = home / ".opencode/bin/opencode"
+ old_calls = tmp_path / "old-calls"
+ network = tmp_path / "network"
+ persist = []
+ tools = tmp_path / "tools"
+ tools.mkdir()
+ env = {
+ key: value
+ for key, value in os.environ.items()
+ if key
+ in {"SYSTEMROOT", "WINDIR", "COMSPEC", "PATHEXT", "PYTHONPATH", "TMPDIR", "TEMP", "TMP", "LANG", "LC_ALL"}
+ or key.startswith(("AVIBE_TEST_", "VIBE_TEST_"))
+ }
+ env.update(HOME=str(home), PATH=os.pathsep.join((str(tools), str(target.parent), "/usr/bin", "/bin")))
+ env.update(
+ AVIBE_HOME=str(home / ".avibe"),
+ CODEX_HOME=str(home / ".codex"),
+ XDG_CONFIG_HOME=str(home / ".config"),
+ XDG_CACHE_HOME=str(home / ".cache"),
+ )
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setattr(Path, "home", lambda: home)
+ monkeypatch.setattr(api, "_command_env_for", lambda _path: dict(env))
+ monkeypatch.setattr(api, "_configured_agent_cli_path", lambda name: str(target))
+ monkeypatch.setattr(api, "_configured_backend_language", lambda: "en")
+ monkeypatch.setattr(api, "is_desktop_backend_path", lambda _path: False)
+ monkeypatch.setattr(api, "is_private_desktop_runtime_path", lambda _path: False)
+ monkeypatch.setattr(api, "is_desktop_managed_runtime", lambda: False)
+ monkeypatch.setattr(api, "_persist_agent_cli_path", lambda name, path: persist.append((name, path)))
+ observations = []
+
+ def observe(backend, path, *, env):
+ health = asyncio.run(probe_cli(backend, path, env=env, timeout_seconds=3))
+ observations.append(health.payload())
+ return health
+
+ monkeypatch.setattr(api, "probe_cli_sync", observe)
+ script = tmp_path / "vendor-boundary.sh"
+ # The actual vendor boundary (opencode.ai/install, inspected 2026-10-12):
+ # command -v -> --version -> same-version exit before downloading. Keep
+ # this executable boundary, not a Python mock of its claimed outcome.
+ script.write_text("""set -euo pipefail
+specific_version=1.2.15
+if command -v opencode >/dev/null 2>&1; then
+ opencode_path=$(which opencode)
+ installed_version=$(opencode --version 2>/dev/null || echo "")
+ if [[ "$installed_version" == "$specific_version" ]]; then exit 0; fi
+fi
+mkdir -p "$HOME/.opencode/bin"
+printf '#!/bin/sh\\nprintf "1.2.15\\\\n"\\n' > "$HOME/.opencode/bin/opencode"
+chmod 755 "$HOME/.opencode/bin/opencode"
+""")
+ curl = executable(
+ tools / "curl",
+ f'from pathlib import Path\nPath({str(network)!r}).write_text("download")\nprint(Path({str(script)!r}).read_text())\n',
+ )
+
+ def resolve(name, **_):
+ if name == "bash":
+ return "/bin/bash"
+ if name == "curl":
+ return str(curl)
+ return str(target) if name in ("opencode", str(target)) and target.exists() else None
+
+ monkeypatch.setattr(api, "resolve_cli_path", resolve)
+ return dict(
+ home=home,
+ target=target,
+ old=old_calls,
+ network=network,
+ env=env,
+ script=script,
+ persist=persist,
+ tools=tools,
+ observations=observations,
+ )
+
+
+def old_cli(case, *, hang=False, misleading=False):
+ body = f'from pathlib import Path\nimport time,sys\nwith Path({str(case["old"])!r}).open("a") as log:log.write("version probe\\n")\n'
+ body += "time.sleep(60)\n" if hang else f"print({'1.2.15' if misleading else 'broken'!r})\nsys.exit(1)\n"
+ return executable(case["target"], body)
+
+
[email protected]("hang,misleading", [(False, False), (True, False), (False, True)])
+def test_native_repair_never_uses_bad_cli_in_bootstrap(native_case, hang, misleading):
+ c = native_case
+ old_cli(c, hang=hang, misleading=misleading)
+ original_env = dict(c["env"])
+ result = api.install_agent("opencode")
+ assert result["ok"] is True, result
+ assert c["old"].exists(), c["observations"]
+ assert c["old"].read_text().splitlines() == ["version probe"] # initial bounded detection only
+ assert c["network"].exists()
+ assert c["persist"] == [("opencode", str(c["target"]))]
+ assert c["env"] == original_env
+ assert subprocess.check_output([str(c["target"]), "--version"], env=c["env"], text=True).strip() == "1.2.15"
+
+
[email protected]("alias", [True, False])
+def test_remaining_resolution_refuses_before_network_or_other_cli(native_case, alias):
+ c = native_case
+ old_cli(c)
+ other = c["home"] / "other-bin"
+ other.mkdir()
+ marker = c["home"] / "other-invoked"
+ if alias:
+ (other / "opencode").symlink_to(c["target"])
+ else:
+ executable(other / "opencode", f'from pathlib import Path\nPath({str(marker)!r}).touch()\nprint("1.2.15")\n')
+ c["env"]["PATH"] = str(other) + os.pathsep + c["env"]["PATH"]
+ result = api.install_agent("opencode")
+ assert result["ok"] is False and result["code"] == "repair_path_conflict"
+ assert c["old"].exists(), c["observations"]
+ assert c["old"].read_text().splitlines() == ["version probe"]
+ assert not marker.exists() and not c["network"].exists() and c["persist"] == []
+
+
+def test_negative_control_vendor_skips_bad_target_for_other_matching_version(native_case):
+ c = native_case
+ old_cli(c)
+ other = c["home"] / "other-bin"
+ other.mkdir()
+ marker = c["home"] / "other-invoked"
+ executable(other / "opencode", f'from pathlib import Path\nPath({str(marker)!r}).touch()\nprint("1.2.15")\n')
+ c["env"]["PATH"] = str(other) + os.pathsep + c["env"]["PATH"]
+ before = c["target"].read_bytes()
+ subprocess.run(["/bin/bash", str(c["script"])], env=c["env"], check=True, timeout=5)
+ assert marker.exists() and c["target"].read_bytes() == before
+ marker.unlink()
+ result = api.install_agent("opencode")
+ assert result["code"] == "repair_path_conflict" and not marker.exists() and not c["network"].exists()
+
+
+def test_startup_hooks_and_imported_functions_cannot_restore_bad_cli(native_case):
+ c = native_case
+ old_cli(c)
+ marker = c["home"] / "hook-ran"
+ hook = c["home"] / "hook.sh"
+ hook.write_text(f"touch {shlex.quote(str(marker))}\nexport PATH={shlex.quote(str(c['target'].parent))}:$PATH\n")
+ c["env"].update(BASH_ENV=str(hook), ENV=str(hook))
+ c["env"]["BASH_FUNC_opencode%%"] = f"() {{ touch {shlex.quote(str(marker))}; echo 1.2.15; }}"
+ result = api.install_agent("opencode")
+ assert result["ok"] and not marker.exists()
+ assert c["old"].exists(), c["observations"]
+ assert c["old"].read_text().splitlines() == ["version probe"]
+ assert c["env"]["BASH_ENV"] == str(hook) # no process/global environment mutation
+
+
[email protected]("outcome", ["unchanged", "missing", "timeout"])
+def test_exit_zero_is_not_repair_success_or_permission_to_switch_path(native_case, outcome):
+ c = native_case
+ old_cli(c)
+ other = c["home"] / "other"
+ other.mkdir()
+ marker = c["home"] / "other-read"
+ executable(other / "opencode", f'from pathlib import Path\nPath({str(marker)!r}).touch()\nprint("1.2.15")\n')
+ c["env"]["PATH"] = str(other) + os.pathsep + c["env"]["PATH"]
+ if outcome == "timeout":
+ old_cli(c, hang=True)
+ code = f"from pathlib import Path; Path({str(c['target'])!r}).unlink()" if outcome == "missing" else "pass"
+ result = api._run_install_command(
+ "opencode",
+ [sys.executable, "-c", code],
+ lambda s: s,
+ mode="repair",
+ env=c["env"],
+ expected_path=str(c["target"]),
+ )
+ assert result["ok"] is False and result["code"] == "cli_readback_failed"
+ assert c["persist"] == [] and not marker.exists()
+
+
+ "backend,package",
+ [("claude", "@anthropic-ai/claude-code"), ("opencode", "opencode-ai"), ("codex", "@openai/codex")],
+)
+def test_npm_provenance_preserves_global_prefix(tmp_path, backend, package):
+ prefix = tmp_path / "npm-prefix"
+ pkg = prefix / "lib/node_modules" / package
+ pkg.mkdir(parents=True)
+ (pkg / "package.json").write_text(json.dumps({"name": package}))
+ target = executable(pkg / "cli.js", 'print("broken")\n')
+ alias = prefix / "bin" / backend
+ alias.parent.mkdir()
+ alias.symlink_to(target)
+ source = identify_repair_source(backend, str(alias), home=tmp_path)
+ assert (
+ source.kind == "npm"
+ and source.prefix == prefix
+ and source.package == package
+ and source.destination == str(alias)
+ )
+
+
+ "backend,package,version_output",
+ [
+ ("claude", "@anthropic-ai/claude-code", "2.1.34 (Claude Code)"),
+ ("opencode", "opencode-ai", "1.2.15"),
+ ],
+)
+def test_broken_npm_cli_is_repaired_by_its_prefix_not_self_update(
+ native_case, monkeypatch, backend, package, version_output
+):
+ c = native_case
+ prefix = c["home"] / "owned npm prefix"
+ pkg = prefix / "lib/node_modules" / package
+ pkg.mkdir(parents=True)
+ (pkg / "package.json").write_text(json.dumps({"name": package}))
+ old = c["home"] / "npm-old-invoked"
+ target = executable(
+ pkg / "cli.js",
+ f'from pathlib import Path\nimport sys\nwith Path({str(old)!r}).open("a") as f:f.write(sys.argv[1]+"\\n")\nsys.exit(1)\n',
+ )
+ alias = prefix / "bin" / backend
+ alias.parent.mkdir()
+ alias.symlink_to(target)
+ calls = c["home"] / "npm-args.json"
+ replacement = "#!" + sys.executable + "\nprint(" + repr(version_output) + ")\n"
+ npm = executable(
+ c["tools"] / "npm",
+ f"import sys,json\nfrom pathlib import Path\nPath({str(calls)!r}).write_text(json.dumps(sys.argv[1:]))\nPath({str(target)!r}).write_text({replacement!r})\n",
+ )
+ 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)
+ assert result["ok"], result
+ assert json.loads(calls.read_text()) == ["install", "--global", "--prefix", str(prefix), package]
+ assert old.read_text().splitlines() == ["--version"]
+ assert c["persist"] == [(backend, str(alias))]
+ assert result["detection"]["status"] == "ok" and result["detection"]["path"] == str(alias)
+
+
[email protected]("configured_bare", [False, True])
[email protected]("outcome", ["missing", "permission", "broken", "healthy"])
+def test_healthy_upgrade_certifies_only_the_selected_executable(native_case, monkeypatch, configured_bare, outcome):
+ c = native_case
+ selected = c["target"]
+ other_marker = c["home"] / "unrelated-probed"
+ other = executable(
+ c["home"] / "other/bin/opencode",
+ f'from pathlib import Path\nPath({str(other_marker)!r}).touch()\nprint("1.1.0")\n',
+ )
+ replacement = "#!" + sys.executable + '\nprint("1.2.16")\n'
+ operation = {
+ "missing": "Path(__file__).unlink()",
+ "permission": "Path(__file__).chmod(0o644)",
+ "broken": "Path(__file__).write_text(" + repr("#!" + sys.executable + '\nprint("Node.js v22.18.0")\n') + ")",
+ "healthy": "Path(__file__).write_text(" + repr(replacement) + ")",
+ }[outcome]
+ executable(
+ selected,
+ 'import sys\nfrom pathlib import Path\nif sys.argv[1] == "--version":\n print("1.2.15")\nelif sys.argv[1] == "upgrade":\n '
+ + operation
+ + "\n",
+ )
+ configured = "opencode" if configured_bare else str(selected)
+ monkeypatch.setattr(api, "_configured_agent_cli_path", lambda _name: configured)
+ # Exercise the real resolver, including basename fallback, but restrict all
+ # discovered candidates to this test's two owned installations.
+ monkeypatch.setattr(
+ api,
+ "resolve_cli_path",
+ lambda binary, **_: api._resolve_cli_path(
+ binary,
+ candidate_paths=lambda _name, **_kw: [selected, other],
+ include_npm_global=False,
+ include_desktop=False,
+ ),
+ )
+ result = api.install_agent("opencode")
+ assert not other_marker.exists()
+ if outcome == "healthy":
+ assert result["ok"] and result["path"] == str(selected)
+ assert result["detection"]["version"] == "1.2.16"
+ assert c["persist"] == [("opencode", str(selected))]
+ else:
+ assert not result["ok"] and result["code"] == "cli_readback_failed"
+ assert c["persist"] == []
+ if outcome in {"missing", "permission"}:
+ # Negative witness: the old post-install resolver WOULD choose the
+ # unrelated installation, so this case can expose the prior bug.
+ assert api.resolve_cli_path(configured) == str(other)
+
+
[email protected]("fresh", [False, True])
[email protected]("outcome", ["missing", "broken", "healthy"])
+def test_codex_npm_certifies_its_declared_prefix_not_an_old_healthy_cli(native_case, monkeypatch, fresh, outcome):
+ c = native_case
+ 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"
+ replacement = (
+ "#!"
+ + sys.executable
+ + "\nprint("
+ + repr("codex-cli 0.162.1" if outcome == "healthy" else "Node.js v22.18.0")
+ + ")\n"
+ )
+ install_body = (
+ f'p=Path(os.environ["NPM_CONFIG_PREFIX"])/"bin/codex";p.parent.mkdir(parents=True,exist_ok=True);p.write_text({replacement!r});p.chmod(0o755)\n'
+ if outcome != "missing"
+ else ""
+ )
+ npm = executable(
+ 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(installed)!r}).touch()\n",
+ )
+ configured = "codex" if fresh else str(old)
+ monkeypatch.setattr(api, "_configured_agent_cli_path", lambda _name: configured)
+ monkeypatch.setattr(api, "_candidate_cli_paths", lambda *_args, **_kwargs: [])
+ monkeypatch.setenv("PATH", c["env"]["PATH"])
+
+ def resolve(binary, **_):
+ if binary == "npm":
+ return str(npm)
+ if binary == "brew":
+ return None
+ if fresh and not installed.exists():
+ return None
+ return str(old) if binary in {"codex", str(old)} else None
+
+ monkeypatch.setattr(api, "resolve_cli_path", resolve)
+ result = api.install_agent("codex")
+ assert installed.exists()
+ 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":
+ assert result["ok"] and result["path"] == str(destination)
+ assert result["detection"]["version"] == "0.162.1"
+ assert c["persist"] == [("codex", str(destination))]
+ else:
+ assert not result["ok"] and result["code"] == "cli_readback_failed"
+ assert c["persist"] == []
+
+
+def test_bare_nonexecutable_npm_cli_outside_home_and_path_keeps_its_prefix(native_case, monkeypatch):
+ from vibe import cli_paths
+
+ c = native_case
+ prefix = c["home"].parent / "custom npm-global prefix"
+ pkg = prefix / "lib/node_modules/@anthropic-ai/claude-code"
+ pkg.mkdir(parents=True)
+ (pkg / "package.json").write_text(json.dumps({"name": "@anthropic-ai/claude-code"}))
+ forbidden = c["home"] / "damaged-cli-was-executed"
+ target = executable(pkg / "cli.js", f"from pathlib import Path\nPath({str(forbidden)!r}).touch()\n")
+ target.chmod(0o644)
+ launcher = prefix / "bin/claude"
+ launcher.parent.mkdir()
+ launcher.symlink_to(target)
+ calls = c["home"] / "repair-prefix.json"
+ replacement = "#!" + sys.executable + '\nprint("2.1.34 (Claude Code)")\n'
+ npm = executable(
+ c["tools"] / "npm",
+ f"import sys,json\nfrom pathlib import Path\nPath({str(calls)!r}).write_text(json.dumps(sys.argv[1:]))\np=Path({str(target)!r});p.write_text({replacement!r});p.chmod(0o755)\n",
+ )
+ monkeypatch.setenv("PATH", c["env"]["PATH"])
+ monkeypatch.setattr(api, "_configured_agent_cli_path", lambda _name: "claude")
+ monkeypatch.setattr(cli_paths, "_npm_global_binary_candidates", lambda name: [launcher] if name == "claude" else [])
+ observed_flags = []
+
+ def candidates(name, *, include_npm_global=True):
+ observed_flags.append(include_npm_global)
+ return [launcher] if name == "claude" and include_npm_global else []
+
+ monkeypatch.setattr(api, "_candidate_cli_paths", candidates)
+
+ def resolve(binary, **_):
+ if binary == "npm":
+ return str(npm)
+ return api._resolve_cli_path(binary, candidate_paths=candidates, include_desktop=False)
+
+ monkeypatch.setattr(api, "resolve_cli_path", resolve)
+ detection = api.detect_cli("claude", "claude")
+ assert detection["found"] and detection["status"] == "broken" and detection["path"] == str(launcher)
+ assert True in observed_flags and not forbidden.exists()
+ result = api.install_agent("claude")
+ assert result["ok"] and result["path"] == str(launcher)
+ assert json.loads(calls.read_text()) == [
+ "install",
+ "--global",
+ "--prefix",
+ str(prefix),
+ "@anthropic-ai/claude-code",
+ ]
+ assert c["persist"] == [("claude", str(launcher))] and not forbidden.exists()
+
+
+def test_cli_path_resolution_defers_npm_prefix_until_standard_candidates_fail(tmp_path, monkeypatch):
+ standard = executable(tmp_path / "standard" / "codex", 'print("codex-cli 0.162.1")\n')
+ npm_candidate = tmp_path / "npm-prefix" / "bin" / "codex"
+ observed_flags = []
+
+ def candidates(name, *, include_npm_global=True):
+ observed_flags.append(include_npm_global)
+ return [standard] if not include_npm_global else [standard, npm_candidate]
+
+ monkeypatch.setattr(cli_paths, "_candidate_cli_paths", candidates)
+ monkeypatch.setenv("PATH", str(tmp_path / "empty-path"))
+
+ assert cli_paths.resolve_cli_path("codex", candidate_paths=candidates, include_desktop=False) == str(standard)
+ assert observed_flags == [False]
+
+
+ "output",
+ [
+ "INFO refreshing models\n1.1.36\n",
+ "INFO loading models\nINFO refreshing models\nopencode 1.1.36\n",
+ ],
+)
+def test_opencode_version_accepts_prefixed_informational_output(output):
+ assert cli_version("opencode", output, "") == "1.1.36"
+
+
+ "output",
+ [
+ "Error: refresh failed 1.1.36\n1.1.36\n",
+ "INFO refreshing models\nError: refresh failed\n1.1.36\n",
+ ],
+)
+def test_opencode_version_rejects_non_informational_prefix(output):
+ assert cli_version("opencode", output, "") is None
+
+
+def test_unknown_installation_is_not_migrated(tmp_path):
+ path = executable(tmp_path / "custom-claude", 'print("broken")\n')
+ assert identify_repair_source("claude", str(path), home=tmp_path) is None
+
+
+def test_path_isolation_removes_equivalent_directory_entries_only(tmp_path):
+ installed = tmp_path / "native"
+ installed.mkdir()
+ alias = tmp_path / "alias"
+ alias.symlink_to(installed, target_is_directory=True)
+ original = {
+ "PATH": os.pathsep.join((str(installed), str(alias), "/usr/bin")),
+ "BASH_ENV": "untrusted",
+ "KEEP": "yes",
+ }
+ result = native_bootstrap_env(original, hide_directory=installed)
+ assert result == {"PATH": "/usr/bin", "KEEP": "yes"} and "BASH_ENV" in original
+
+
[email protected]("outcome", ["missing", "broken", "healthy"])
+def test_windows_npm_upgrade_declares_active_prefix_and_never_certifies_old_cli(tmp_path, monkeypatch, outcome):
+ """A real npm child and real target children exercise the Windows contract on POSIX."""
+ home = tmp_path / "isolated home"
+ tools = tmp_path / "tools"
+ tools.mkdir()
+ prefix_a = home / "npm-prefix-a"
+ prefix_b = home / "npm-prefix-b"
+ old_marker = home / "old-probed"
+ new_marker = home / "new-probed"
+ old = executable(
+ prefix_a / "codex.cmd",
+ f'from pathlib import Path\nPath({str(old_marker)!r}).touch()\nprint("codex-cli 0.161.0")\n',
+ )
+ replacement = (
+ "#!"
+ + sys.executable
+ + "\nfrom pathlib import Path\nPath("
+ + repr(str(new_marker))
+ + ").touch()\n"
+ + (
+ 'print("codex-cli 0.162.1")\n'
+ if outcome == "healthy"
+ else 'print("Node.js v22.18.0")\n'
+ if outcome == "broken"
+ else ""
+ )
+ )
+ npm = executable(
+ tools / "npm",
+ f'import sys\nfrom pathlib import Path\nif sys.argv[1:] == ["config", "get", "prefix"]:\n print({str(prefix_b)!r}); raise SystemExit(0)\nif sys.argv[1:] == ["install", "-g", "@openai/codex"]:\n p=Path({str(prefix_b / "codex.cmd")!r}); p.parent.mkdir(parents=True,exist_ok=True)\n'
+ + (f"p.write_text({replacement!r}); p.chmod(0o755)\n" if outcome != "missing" else "")
+ + "raise SystemExit(0)\n",
+ )
+ env = fixture_env(tmp_path)
+ env.update(HOME=str(home), AVIBE_HOME=str(home / ".avibe"))
+ monkeypatch.setenv("AVIBE_HOME", str(home / ".avibe"))
+ monkeypatch.setattr(api.paths, "get_state_dir", lambda: home / "state")
+ env["NPM_CONFIG_PREFIX"] = str(prefix_b)
+ monkeypatch.setattr(api, "_command_env_for", lambda _path: dict(env))
+ monkeypatch.setattr(api, "_configured_agent_cli_path", lambda _name: "codex")
+ monkeypatch.setattr(api, "_is_npm_codex_install", lambda _path: True)
+ monkeypatch.setattr(api, "_is_homebrew_codex_install", lambda _path: False)
+ monkeypatch.setattr(api, "_npm_prefix_for_existing_codex_install", lambda *_args: None)
+ monkeypatch.setattr(
+ api,
+ "resolve_cli_path",
+ lambda name, **_kwargs: str(old) if name == "codex" else str(npm) if name == "npm" else None,
+ )
+ persisted = []
+ monkeypatch.setattr(api, "_persist_agent_cli_path", lambda _name, path: persisted.append(path))
+ observed = []
+
+ def observe(binary, backend):
+ path = str(old) if binary == "codex" else binary
+ observed.append(path)
+ if not Path(path).is_file() or not os.access(path, os.X_OK):
+ status = "missing" if not Path(path).exists() else "broken"
+ return api.CliHealth(False, path if Path(path).exists() else None, status).payload()
+ result = subprocess.run([path, "--version"], env=env, capture_output=True, text=True, check=False)
+ version = cli_version(backend, result.stdout, result.stderr) if result.returncode == 0 else None
+ return api.CliHealth(
+ True, path, "ok" if version else "broken", version=version, reason=None if version else "probe_failed"
+ ).payload()
+
+ monkeypatch.setattr(api, "detect_cli", observe)
+ observe(str(old), "codex")
+ result = api._run_install_command(
+ "codex",
+ [str(npm), "install", "-g", "@openai/codex"],
+ lambda value: value,
+ mode="upgrade",
+ env=env,
+ expected_path=str(prefix_b / "codex.cmd"),
+ )
+ target = str(prefix_b / "codex.cmd")
+ assert observed == [str(old), target]
+ assert old_marker.exists() and new_marker.exists() is (outcome != "missing")
+ if outcome == "healthy":
+ assert result["ok"] and result["path"] == target and persisted == [target]
+ else:
+ assert not result["ok"] and result["code"] == "cli_readback_failed" and persisted == []
+ assert result.get("detection", {}).get("path") in {target, None}
+
+
+def test_windows_npm_install_env_declares_prefix_from_real_npm_child(tmp_path, monkeypatch):
+ prefix = tmp_path / "active-prefix"
+ npm = executable(
+ tmp_path / "npm",
+ f'import sys\nif sys.argv[1:] == ["config", "get", "prefix"]: print({str(prefix)!r}); raise SystemExit(0)\nraise SystemExit(2)\n',
+ )
+ monkeypatch.setattr(api.os, "name", "nt", raising=False)
+ monkeypatch.setattr(api, "_command_env_for", lambda _path: {"PATH": str(tmp_path)})
+ observed = subprocess.run([str(npm), "config", "get", "prefix"], env={"PATH": str(tmp_path)}, capture_output=True, text=True, check=True)
+ monkeypatch.setattr(api, "_npm_prefix_for", lambda _path: Path(observed.stdout.strip()))
+ env = api._codex_npm_install_env(str(npm))
+ normalized_prefix = env["NPM_CONFIG_PREFIX"].replace("\\", "/")
+ assert env is not None and normalized_prefix == str(prefix)
+ assert env["PATH"].split(os.pathsep)[0].replace("\\", "/") == str(prefix)
+ assert normalized_prefix + "/codex.cmd" == str(prefix / "codex.cmd")
+
+
+def test_windows_npm_prefix_query_failure_fails_closed(tmp_path, monkeypatch):
+ npm = executable(tmp_path / "npm", "import sys\nraise SystemExit(1)\n")
+ monkeypatch.setattr(api.os, "name", "nt", raising=False)
+ monkeypatch.setattr(api, "_command_env_for", lambda _path: {"PATH": str(tmp_path)})
+ assert api._codex_npm_install_env(str(npm)) is None
+ assert api._declared_codex_npm_target(None) is None
+
+
+def test_cli_discovery_preserves_path_before_npm_for_presence_and_run(tmp_path, monkeypatch):
+ path_dir = tmp_path / "path-bin"
+ npm_dir = tmp_path / "npm-bin"
+ path_cli = path_dir / "codex"
+ npm_cli = npm_dir / "codex"
+ path_dir.mkdir()
+ npm_dir.mkdir()
+ path_cli.write_text("#!/bin/sh\n", encoding="utf-8")
+ npm_cli.write_text("#!/bin/sh\n", encoding="utf-8")
+ path_cli.chmod(0o644)
+ npm_cli.chmod(0o644)
+ monkeypatch.setenv("PATH", str(path_dir))
+
+ def candidates(binary, *, include_npm_global=True):
+ assert binary == "codex"
+ return [npm_cli] if include_npm_global else []
+
+ monkeypatch.setattr(api, "_candidate_cli_paths", candidates)
+ assert api.resolve_cli_path("codex") is None
+ backend, detected = api._cli_detection_target("codex", "codex")
+ assert backend == "codex" and detected == str(path_cli.absolute())
+
+
+def _fake_homebrew_cask_run(brew: Path, prefix: Path, *, version: str = "1.2.3", query_ok: bool = True):
+ def fake_run(cmd, **_kwargs):
+ if cmd == [str(brew), "--prefix"]:
+ return SimpleNamespace(returncode=0, stdout=str(prefix) + "\n", stderr="")
+ if cmd == [str(brew), "info", "--cask", "--json=v2", "--installed", "codex"]:
+ if not query_ok:
+ return SimpleNamespace(returncode=1, stdout="", stderr="metadata unavailable")
+ return SimpleNamespace(
+ returncode=0,
+ stdout=json.dumps({"casks": [{"token": "codex", "installed": version}]}),
+ stderr="",
+ )
+ raise AssertionError(f"unexpected Homebrew command: {cmd!r}")
+
+ return fake_run
+
+
+def test_homebrew_symlinked_stable_bin_target_is_attributable(tmp_path, monkeypatch):
+ prefix = tmp_path / "homebrew"
+ brew_repo = executable(prefix / "Homebrew/bin/brew", "#!/bin/sh\n")
+ brew = prefix / "bin/brew"
+ brew.parent.mkdir(parents=True, exist_ok=True)
+ brew.symlink_to(brew_repo)
+ payload = prefix / "Caskroom/codex/1.2.3/libexec"
+ target = executable(payload / "codex", 'print("codex-cli 0.162.1")\n')
+ launcher = prefix / "bin/codex"
+ launcher.symlink_to(target)
+
+ monkeypatch.setattr(api.subprocess, "run", _fake_homebrew_cask_run(brew, prefix))
+ assert api._homebrew_codex_target(str(brew), str(launcher)) == str(launcher)
+
+
+def test_homebrew_codex_attribution_fails_closed_for_ambiguous_targets(tmp_path, monkeypatch):
+ prefix = tmp_path / "homebrew"
+ brew = executable(prefix / "bin/brew", "#!/bin/sh\n")
+ payload = prefix / "Caskroom/codex/1.2.3/libexec"
+ target = executable(payload / "codex", 'print("codex-cli 0.162.1")\n')
+ outside = executable(tmp_path / "outside/codex", 'print("codex-cli 0.162.1")\n')
+ regular = prefix / "bin/codex"
+ regular.parent.mkdir(parents=True, exist_ok=True)
+ regular.write_text("#!/bin/sh\n", encoding="utf-8")
+ regular.chmod(0o755)
+ other_prefix = tmp_path / "other-homebrew"
+ other_target = executable(other_prefix / "Caskroom/codex/1.2.3/libexec/codex", 'print("codex-cli 0.162.1")\n')
+ other_launcher = other_prefix / "bin/codex"
+ other_launcher.parent.mkdir(parents=True, exist_ok=True)
+ other_launcher.symlink_to(other_target)
+ nested = prefix / "bin/nested/codex"
+ nested.parent.mkdir(parents=True, exist_ok=True)
+ nested.symlink_to(target)
+ unrelated_target = executable(prefix / "Caskroom/other/1.2.3/libexec/codex", 'print("codex-cli 0.162.1")\n')
+
+ monkeypatch.setattr(api.subprocess, "run", _fake_homebrew_cask_run(brew, prefix))
+ assert api._homebrew_codex_target(str(brew), str(regular)) is None
+ assert api._homebrew_codex_target(str(brew), str(other_launcher)) is None
+ assert api._homebrew_codex_target(str(brew), str(nested)) is None
+ regular.unlink()
+ regular.symlink_to(outside)
+ assert api._homebrew_codex_target(str(brew), str(regular)) is None
+ regular.unlink()
+ regular.symlink_to(unrelated_target)
+ assert api._homebrew_codex_target(str(brew), str(regular)) is None
+ monkeypatch.setattr(api, "resolve_cli_path", lambda name, **_kwargs: str(brew) if name == "brew" else None)
+ monkeypatch.setattr(api, "_is_npm_codex_install", lambda _path: False)
+ monkeypatch.setattr(api, "_codex_cli_supports_update", lambda _path: pytest.fail("ambiguous target must not self-update"))
+ result = api._codex_upgrade_command(str(regular))
+ assert result["code"] == "cli_target_unknown"
+ assert api._codex_upgrade_command(str(other_launcher))["code"] == "cli_target_unknown"
+ assert api._codex_upgrade_command(str(nested))["code"] == "cli_target_unknown"
+
+
[email protected]("query_ok", [True, False], ids=["installed", "metadata-unknown"])
+def test_codex_custom_self_update_ignores_unrelated_homebrew_cask(tmp_path, monkeypatch, query_ok):
+ prefix = tmp_path / "homebrew"
+ brew = executable(prefix / "bin/brew", "#!/bin/sh\n")
+ custom = executable(tmp_path / "custom/bin/codex", 'print("codex-cli 0.162.1")\n')
+
+ monkeypatch.setattr(api.subprocess, "run", _fake_homebrew_cask_run(brew, prefix, query_ok=query_ok))
+ monkeypatch.setattr(api, "resolve_cli_path", lambda name, **_kwargs: str(brew) if name == "brew" else None)
+ monkeypatch.setattr(api, "_is_npm_codex_install", lambda _path: False)
+ monkeypatch.setattr(api, "_codex_cli_supports_update", lambda path: path == str(custom))
+
+ assert api._codex_upgrade_command(str(custom)) == ([str(custom), "update"], None)
+
+
+def test_homebrew_codex_malformed_metadata_refuses_upgrade(tmp_path, monkeypatch):
+ prefix = tmp_path / "homebrew"
+ brew = executable(prefix / "bin/brew", "#!/bin/sh\n")
+ launcher = executable(prefix / "bin/codex", 'print("codex-cli 0.162.1")\n')
+
+ def fake_run(cmd, **_kwargs):
+ if cmd == [str(brew), "--prefix"]:
+ return SimpleNamespace(returncode=0, stdout=str(prefix) + "\n", stderr="")
+ if cmd == [str(brew), "info", "--cask", "--json=v2", "--installed", "codex"]:
+ return SimpleNamespace(
+ returncode=0,
+ stdout=json.dumps({"casks": [{"token": "codex", "installed": "../escape"}]}),
+ stderr="",
+ )
+ raise AssertionError(f"unexpected Homebrew command: {cmd!r}")
+
+ monkeypatch.setattr(api.subprocess, "run", fake_run)
+ monkeypatch.setattr(api, "resolve_cli_path", lambda name, **_kwargs: str(brew) if name == "brew" else None)
+ monkeypatch.setattr(api, "_is_npm_codex_install", lambda _path: False)
+ monkeypatch.setattr(api, "_codex_cli_supports_update", lambda _path: pytest.fail("malformed metadata must not self-update"))
+
+ result = api._codex_upgrade_command(str(launcher))
+ assert result["code"] == "cli_target_unknown"
+
+
+def test_homebrew_codex_metadata_query_failure_refuses_upgrade(tmp_path, monkeypatch):
+ prefix = tmp_path / "homebrew"
+ brew = executable(prefix / "bin/brew", "#!/bin/sh\n")
+ launcher = executable(prefix / "bin/codex", 'print("codex-cli 0.162.1")\n')
+ monkeypatch.setattr(api.subprocess, "run", _fake_homebrew_cask_run(brew, prefix, query_ok=False))
+ monkeypatch.setattr(api, "resolve_cli_path", lambda name, **_kwargs: str(brew) if name == "brew" else None)
+ monkeypatch.setattr(api, "_is_npm_codex_install", lambda _path: False)
+ monkeypatch.setattr(api, "_codex_cli_supports_update", lambda _path: pytest.fail("ambiguous target must not self-update"))
+ result = api._codex_upgrade_command(str(launcher))
+ assert result["code"] == "cli_target_unknown"
+
+
+def test_codex_homebrew_upgrade_plan_binds_the_stable_launcher(tmp_path, monkeypatch):
+ prefix = tmp_path / "homebrew"
+ brew = executable(prefix / "bin/brew", "#!/bin/sh\n")
+ target = executable(prefix / "Caskroom/codex/1.2.3/libexec/codex", 'print("codex-cli 0.162.1")\n')
+ launcher = prefix / "bin/codex"
+ launcher.symlink_to(target)
+
+ monkeypatch.setattr(api.subprocess, "run", _fake_homebrew_cask_run(brew, prefix))
+ monkeypatch.setattr(api, "resolve_cli_path", lambda name, **_kwargs: str(brew) if name == "brew" else None)
+ monkeypatch.setattr(api, "_is_npm_codex_install", lambda _path: False)
+ plan = api._codex_upgrade_command(str(launcher))
+ assert plan == ([str(brew), "upgrade", "--cask", "codex"], None)
+
+
+def test_codex_homebrew_upgrade_readback_rechecks_identity(tmp_path, monkeypatch):
+ prefix = tmp_path / "homebrew"
+ brew = executable(prefix / "bin/brew", "#!/bin/sh\n")
+ payload = prefix / "Caskroom/codex/1.2.3/libexec"
+ target = executable(payload / "codex", 'print("codex-cli 0.162.1")\n')
+ escape = executable(tmp_path / "escape/codex", 'print("codex-cli 0.162.1")\n')
+ launcher = prefix / "bin/codex"
+ launcher.symlink_to(target)
+ installer = executable(
+ tmp_path / "upgrade",
+ f'from pathlib import Path\np=Path({str(launcher)!r}); p.unlink(); p.symlink_to({str(escape)!r})\n',
+ )
+ monkeypatch.setattr(api.subprocess, "run", _fake_homebrew_cask_run(brew, prefix))
+ monkeypatch.setattr(api, "detect_cli", lambda _binary, _backend: api.CliHealth(True, str(launcher), "ok").payload())
+ persisted = []
+ monkeypatch.setattr(api, "_persist_agent_cli_path", lambda _name, path: persisted.append(path))
+ result = api._run_install_command(
+ "codex",
+ [str(installer)],
+ lambda value: value,
+ mode="upgrade",
+ expected_path=str(launcher),
+ readback_validator=lambda path: api._homebrew_codex_target(str(brew), path) == str(launcher),
+ )
+ assert not result["ok"] and result["code"] == "cli_readback_failed" and persisted == []
diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.py
index 626833d9a..8006f4830 100644
--- a/tests/test_member_management_parity.py
+++ b/tests/test_member_management_parity.py
@@ -496,7 +496,9 @@ def test_remote_management_handlers_reach_only_stubbed_host_effects(management_h
return run
- monkeypatch.setattr(api, "get_backend_runtime", effect("runtime"))
+ async def runtime_effect(*args, **kwargs):
+ return effect("runtime")(*args, **kwargs)
+ monkeypatch.setattr(api, "get_backend_runtime_async", runtime_effect)
monkeypatch.setattr(api, "start_dependency_install_job", effect("dependency"))
monkeypatch.setattr(api, "slack_auth_test", effect("platform"))
monkeypatch.setattr(cli, "_doctor", effect("doctor"))
@@ -517,7 +519,7 @@ def test_remote_management_handlers_reach_only_stubbed_host_effects(management_h
["runtime", "dependency", "platform", "doctor", "transport"] if role in {"owner", "member"} else []
)
if calls:
- assert calls[0][1] == ("claude",)
+ assert calls[0][1] == ("claude", None)
assert calls[1][1] == ("avault",)
assert calls[2][1][0] == "test-token"
assert calls[3][2]["deep"] is True
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index a79125e3d..da7f4b4ba 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -32,6 +32,19 @@ from vibe import api, backend_model_catalog, cli_paths
from vibe.opencode_config import parse_jsonc_object
+def healthy_cli_observation(monkeypatch):
+ """Command-selection tests assume a usable fake CLI, not a real supervisor.
+
+ Filesystem/probe/read-back failure contracts are exercised with real owned
+ children in test_cli_health, test_cli_repair and test_cli_detection_api.
+ """
+ def observe(binary, backend=None):
+ path = binary if api.os.path.isabs(binary) else api.resolve_cli_path(binary)
+ return api.CliHealth(bool(path), path, "ok" if path else "missing", "1.0.0" if path else None).payload()
+ monkeypatch.setattr(api, "detect_cli", observe)
+
+
class _PopenFromRun:
def __init__(self, cmd, *args, **kwargs):
result = api.subprocess.run(cmd, **kwargs)
@@ -1931,6 +1944,7 @@ def test_detect_cli_finds_codex_in_npm_global_prefix(monkeypatch, tmp_path, only
assert result["path"] == str(codex_path)
[email protected]("healthy_cli_observation")
def test_install_agent_blocks_private_desktop_codex_self_update(monkeypatch, tmp_path):
runtime_root = tmp_path / "runtime" / "3.1.0" / ("a" * 16)
codex_path = runtime_root / "tools" / "bin" / "codex"
@@ -1967,7 +1981,7 @@ def test_backend_runtime_skips_latest_probe_for_private_desktop_codex(monkeypatc
monkeypatch.setenv("AVIBE_DESKTOP_RUNTIME_ROOT", str(runtime_root))
monkeypatch.setattr(api.V2Config, "load", staticmethod(lambda: config))
monkeypatch.setattr(api, "resolve_cli_path", lambda _binary: str(codex_path))
- monkeypatch.setattr(api, "_cached_version", lambda _name, _path: "1.2.3")
+ monkeypatch.setattr(api, "detect_cli_async", AsyncMock(return_value=api.CliHealth(True, str(codex_path), "ok", "1.2.3").payload()))
monkeypatch.setattr(
api,
"_cached_latest",
@@ -1983,6 +1997,7 @@ def test_backend_runtime_skips_latest_probe_for_private_desktop_codex(monkeypatc
assert result["managed_by"] == "desktop"
[email protected]("healthy_cli_observation")
def test_install_agent_upgrades_exact_configured_external_path(monkeypatch, tmp_path):
external = tmp_path / "custom" / "claude"
external.parent.mkdir()
@@ -2020,9 +2035,10 @@ def test_install_agent_upgrades_exact_configured_external_path(monkeypatch, tmp_
assert result["ok"] is True
assert result["path"] == str(external)
assert commands == [[str(external), "update"]]
- assert resolved == [str(external), str(external)]
+ assert resolved == [str(external)] # post-upgrade uses the bound path, not rediscovery
[email protected]("healthy_cli_observation")
def test_install_agent_uses_private_desktop_installer_when_external_is_missing(monkeypatch, tmp_path):
installed = tmp_path / "backends" / "codex" / "releases" / "new" / "codex"
monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")
@@ -2030,7 +2046,7 @@ def test_install_agent_uses_private_desktop_installer_when_external_is_missing(m
config = api.V2Config.default()
config.agents.codex.cli_path = "codex"
config.save()
- invalidated: list[str] = []
+ read_back: list[tuple[str, str]] = []
def fake_install(name, *, activate):
assert name == "codex"
@@ -2040,7 +2056,10 @@ def test_install_agent_uses_private_desktop_installer_when_external_is_missing(m
monkeypatch.setattr(api, "resolve_cli_path", lambda value: None)
monkeypatch.setattr(api, "desktop_backend_toolchain", lambda: object())
monkeypatch.setattr(api, "install_desktop_backend", fake_install)
- monkeypatch.setattr(api, "_invalidate_version_cache", invalidated.append)
+ def verified(binary, backend):
+ read_back.append((binary, backend))
+ return api.CliHealth(True, binary, "ok", "1.2.3").payload()
+ monkeypatch.setattr(api, "detect_cli", verified)
monkeypatch.setattr(
api.subprocess,
"Popen",
@@ -2054,7 +2073,7 @@ def test_install_agent_uses_private_desktop_installer_when_external_is_missing(m
assert result["path"] == str(installed)
assert result["message"] == "Codex installed successfully."
assert api.V2Config.load().agents.codex.cli_path == str(installed)
- assert invalidated == ["codex"]
+ assert read_back == [(str(installed), "codex")]
def test_desktop_backend_install_localizes_structured_failure(monkeypatch):
@@ -2108,6 +2127,7 @@ def test_desktop_runtime_does_not_fall_back_to_global_installer(monkeypatch, bac
@pytest.mark.parametrize("backend", ["claude", "codex", "opencode"])
[email protected]("healthy_cli_observation")
def test_install_agent_updates_existing_private_backend(monkeypatch, tmp_path, backend):
existing = tmp_path / "backends" / backend / "releases" / "old" / backend
config = SimpleNamespace(
@@ -2131,6 +2151,7 @@ def test_install_agent_updates_existing_private_backend(monkeypatch, tmp_path, b
@pytest.mark.parametrize("backend", ["claude", "codex", "opencode"])
[email protected]("healthy_cli_observation")
def test_install_agent_never_upgrades_an_external_cli_for_a_missing_private_backend(
monkeypatch, tmp_path, backend
):
@@ -2176,6 +2197,7 @@ def test_install_agent_never_upgrades_an_external_cli_for_a_missing_private_back
assert managed == [backend], "the missing private backend was not reinstalled privately"
[email protected]("healthy_cli_observation")
def test_install_agent_blocks_a_missing_private_runtime_codex_without_reaching_the_external_one(
monkeypatch, tmp_path
):
@@ -2220,7 +2242,7 @@ def test_backend_runtime_checks_updates_for_private_backend(monkeypatch, tmp_pat
monkeypatch.setattr(api, "resolve_cli_path", lambda _value: str(managed))
monkeypatch.setattr(api, "is_desktop_backend_path", lambda path: path == str(managed))
monkeypatch.setattr(api, "is_private_desktop_runtime_path", lambda _path: False)
- monkeypatch.setattr(api, "_cached_version", lambda _name, _path: "1.0.0")
+ monkeypatch.setattr(api, "detect_cli_async", AsyncMock(return_value=api.CliHealth(True, str(managed), "ok", "1.0.0").payload()))
monkeypatch.setattr(api, "_cached_latest", lambda _name: "1.1.0")
monkeypatch.setattr(api, "_opencode_process_status", lambda: "stopped")
monkeypatch.setattr(api, "_codex_process_status", lambda _path: "stopped")
@@ -2355,6 +2377,7 @@ def test_resolve_cli_paths_preserves_completed_paths_when_other_probes_fail(
}
[email protected]("healthy_cli_observation")
def test_install_agent_returns_resolved_path(monkeypatch):
class CompletedProcess:
returncode = 0
@@ -2376,6 +2399,7 @@ def test_install_agent_returns_resolved_path(monkeypatch):
assert result["path"] == "/Users/test/.opencode/bin/opencode"
[email protected]("healthy_cli_observation")
def test_install_agent_refuses_a_second_concurrent_install_of_one_backend(monkeypatch):
# Settings installs in the UI process and auto-update in the controller;
# both reach the CLI only through ``install_agent``.
@@ -2414,6 +2438,7 @@ def test_install_agent_refuses_a_second_concurrent_install_of_one_backend(monkey
assert api.install_agent("opencode")["ok"] is True
[email protected]("healthy_cli_observation")
def test_install_codex_fresh_install_uses_resolved_npm(monkeypatch, tmp_path):
# Fresh-install path: codex is not yet on disk, but npm is resolvable.
# install_agent must shell out to `npm install -g @openai/codex` and
@@ -2430,8 +2455,9 @@ def test_install_codex_fresh_install_uses_resolved_npm(monkeypatch, tmp_path):
calls.append((cmd, kwargs.get("env", {})))
return CompletedProcess()
- # Codex is missing before install, present after.
- codex_resolve = iter([None, "/Users/test/.nvm/versions/node/v22.18.0/bin/codex"])
+ # Discovery is consulted before installation only. The command declares
+ # its user-prefix target; an unrelated Node prefix cannot certify it.
+ codex_resolve = iter([None, None])
def fake_resolve(binary):
if binary == "npm":
@@ -2452,9 +2478,10 @@ def test_install_codex_fresh_install_uses_resolved_npm(monkeypatch, tmp_path):
assert calls[0][0] == ["/Users/test/.nvm/versions/node/v22.18.0/bin/npm", "install", "-g", "@openai/codex"]
assert calls[0][1]["NPM_CONFIG_PREFIX"] == str(api.Path.home() / ".local")
assert calls[0][1]["PATH"].split(api.os.pathsep)[0] == str(api.Path.home() / ".local" / "bin")
- assert result["path"] == "/Users/test/.nvm/versions/node/v22.18.0/bin/codex"
+ assert result["path"] == str(tmp_path / ".local" / "bin" / "codex")
[email protected]("healthy_cli_observation")
def test_install_codex_npm_install_runs_npm_upgrade(monkeypatch, tmp_path):
# Npm-owned Codex installs should upgrade through npm, not through a
# different installer and not by blindly invoking the CLI self-updater. The
@@ -2480,6 +2507,9 @@ def test_install_codex_npm_install_runs_npm_upgrade(monkeypatch, tmp_path):
if cmd == [str(npm_path), "config", "get", "prefix"]:
return CompletedProcess(stdout=f"{npm_path.parent.parent}\n")
if cmd == [str(npm_path), "install", "-g", "@openai/codex"]:
+ # The declared launcher and configured package entry are aliases
+ # of the same installed artifact, so retain the selected path.
+ (npm_path.parent / "codex").symlink_to(codex_path)
return CompletedProcess(stdout="updated")
raise AssertionError(f"unexpected command: {cmd}")
@@ -2506,14 +2536,19 @@ def test_install_codex_npm_install_runs_npm_upgrade(monkeypatch, tmp_path):
assert result["path"] == str(codex_path)
[email protected]("healthy_cli_observation")
def test_install_codex_homebrew_install_runs_brew_upgrade(monkeypatch, tmp_path):
- brew_path = tmp_path / "homebrew" / "bin" / "brew"
+ prefix = tmp_path / "homebrew"
+ brew_path = prefix / "bin" / "brew"
brew_path.parent.mkdir(parents=True)
brew_path.write_text("#!/bin/sh\n")
brew_path.chmod(0o755)
- codex_path = tmp_path / "homebrew" / "bin" / "codex"
- codex_path.write_text("#!/bin/sh\n")
- codex_path.chmod(0o755)
+ target = prefix / "Caskroom" / "codex" / "1.2.3" / "libexec" / "codex"
+ target.parent.mkdir(parents=True)
+ target.write_text("#!/bin/sh\n")
+ target.chmod(0o755)
+ codex_path = prefix / "bin" / "codex"
+ codex_path.symlink_to(target)
calls = []
class CompletedProcess:
@@ -2524,12 +2559,10 @@ def test_install_codex_homebrew_install_runs_brew_upgrade(monkeypatch, tmp_path)
def fake_run(cmd, **kwargs):
calls.append((cmd, kwargs.get("env", {})))
- if cmd == [str(brew_path), "list", "--cask", "codex"]:
- return CompletedProcess()
if cmd == [str(brew_path), "--prefix"]:
- return CompletedProcess(stdout=f"{tmp_path / 'homebrew'}\n")
- if cmd == [str(brew_path), "--prefix", "--cask"]:
- return CompletedProcess(stdout=f"{tmp_path / 'homebrew' / 'Caskroom'}\n")
+ return CompletedProcess(stdout=f"{prefix}\n")
+ if cmd == [str(brew_path), "info", "--cask", "--json=v2", "--installed", "codex"]:
+ return CompletedProcess(stdout=json.dumps({"casks": [{"token": "codex", "installed": "1.2.3"}]}))
if cmd == [str(brew_path), "upgrade", "--cask", "codex"]:
return CompletedProcess(stdout="upgraded")
raise AssertionError(f"unexpected command: {cmd}")
@@ -2554,15 +2587,21 @@ def test_install_codex_homebrew_install_runs_brew_upgrade(monkeypatch, tmp_path)
assert [str(brew_path), "upgrade", "--cask", "codex"] in [call[0] for call in calls]
[email protected]("healthy_cli_observation")
def test_install_codex_prefers_homebrew_when_npm_shares_prefix(monkeypatch, tmp_path):
prefix = tmp_path / "homebrew"
brew_path = prefix / "bin" / "brew"
npm_path = prefix / "bin" / "npm"
codex_path = prefix / "bin" / "codex"
- for path in (brew_path, npm_path, codex_path):
+ for path in (brew_path, npm_path):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("#!/bin/sh\n")
path.chmod(0o755)
+ target = prefix / "Caskroom" / "codex" / "1.2.3" / "libexec" / "codex"
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text("#!/bin/sh\n")
+ target.chmod(0o755)
+ codex_path.symlink_to(target)
calls = []
class CompletedProcess:
@@ -2573,12 +2612,10 @@ def test_install_codex_prefers_homebrew_when_npm_shares_prefix(monkeypatch, tmp_
def fake_run(cmd, **kwargs):
calls.append((cmd, kwargs.get("env", {})))
- if cmd == [str(brew_path), "list", "--cask", "codex"]:
- return CompletedProcess()
if cmd == [str(brew_path), "--prefix"]:
return CompletedProcess(stdout=f"{prefix}\n")
- if cmd == [str(brew_path), "--prefix", "--cask"]:
- return CompletedProcess(stdout=f"{prefix / 'Caskroom'}\n")
+ if cmd == [str(brew_path), "info", "--cask", "--json=v2", "--installed", "codex"]:
+ return CompletedProcess(stdout=json.dumps({"casks": [{"token": "codex", "installed": "1.2.3"}]}))
if cmd == [str(npm_path), "config", "get", "prefix"]:
return CompletedProcess(stdout=f"{prefix}\n")
if cmd == [str(brew_path), "upgrade", "--cask", "codex"]:
@@ -2609,6 +2646,7 @@ def test_install_codex_prefers_homebrew_when_npm_shares_prefix(monkeypatch, tmp_
assert [str(npm_path), "install", "-g", "@openai/codex"] not in commands
[email protected]("healthy_cli_observation")
def test_install_codex_unknown_install_falls_back_to_cli_update(monkeypatch, tmp_path, only_tmp_binaries):
codex_path = tmp_path / "bin" / "codex"
codex_path.parent.mkdir(parents=True)
@@ -2648,6 +2686,7 @@ def test_install_codex_unknown_install_falls_back_to_cli_update(monkeypatch, tmp
assert result["path"] == str(codex_path)
[email protected]("healthy_cli_observation")
def test_install_codex_unknown_install_without_update_command_fails(monkeypatch, tmp_path):
codex_path = tmp_path / "bin" / "codex"
codex_path.parent.mkdir(parents=True)
@@ -2681,6 +2720,7 @@ def test_install_codex_unknown_install_without_update_command_fails(monkeypatch,
assert "does not expose an update command" in result["message"]
[email protected]("healthy_cli_observation")
def test_install_codex_npm_install_without_npm_fails(monkeypatch, tmp_path):
codex_path = tmp_path / "lib" / "node_modules" / "@openai" / "codex" / "bin" / "codex.js"
codex_path.parent.mkdir(parents=True)
@@ -2714,6 +2754,7 @@ def test_discord_list_channels_rejects_empty_guild_id(monkeypatch):
assert result["error"] == "Discord guild_id is required"
[email protected]("healthy_cli_observation")
def test_install_codex_detects_existing_install_via_npm_prefix_and_upgrades_with_npm(monkeypatch, tmp_path, only_tmp_binaries):
# Codex already installed under the npm global prefix; resolve_cli_path
# must discover it (via `npm config get prefix`) and install_agent must
@@ -2760,6 +2801,7 @@ def test_install_codex_detects_existing_install_via_npm_prefix_and_upgrades_with
assert update_calls[0][1]["PATH"].split(api.os.pathsep)[0] == str(prefix_path / "bin")
[email protected]("healthy_cli_observation")
def test_install_codex_symlinked_npm_install_upgrades_in_real_prefix(monkeypatch, tmp_path, only_tmp_binaries):
# Regression coverage for the Incus layout: ~/.local/bin/codex is a shim to
# ~/.npm-global/bin/codex. Running npm with prefix ~/.local tries to replace
@@ -2820,6 +2862,7 @@ def test_install_codex_symlinked_npm_install_upgrades_in_real_prefix(monkeypatch
assert update_calls[0][1]["PATH"].split(api.os.pathsep)[0] == str(prefix_path / "bin")
[email protected]("healthy_cli_observation")
def test_install_codex_project_local_node_modules_does_not_become_prefix(
monkeypatch,
tmp_path,
diff --git a/tests/test_ui_server_install.py b/tests/test_ui_server_install.py
index 9e23575b6..4a8446ea5 100644
--- a/tests/test_ui_server_install.py
+++ b/tests/test_ui_server_install.py
@@ -160,7 +160,7 @@ def test_dependency_install_route_allows_model_hub_engine(monkeypatch, tmp_path)
def test_install_job_fails_when_runtime_refresh_fails(monkeypatch, backend):
monkeypatch.setattr(api, "is_agent_backend", lambda name: name == backend)
monkeypatch.setattr(api, "supports_runtime_refresh", lambda name: name == backend)
- monkeypatch.setattr(api, "_agent_runtime_fingerprint", lambda name: None)
+ monkeypatch.setattr(api, "_agent_runtime_fingerprint", lambda name, detection=None: None)
monkeypatch.setattr(
api,
"install_agent",
@@ -169,6 +169,7 @@ def test_install_job_fails_when_runtime_refresh_fails(monkeypatch, backend):
"message": "Installed",
"output": "done",
"path": f"/usr/local/bin/{backend}",
+ "detection": api.CliHealth(True, f"/usr/local/bin/{backend}", "ok", "1.0.0").payload(),
},
)
monkeypatch.setattr(api, "restart_backend", lambda name, **kwargs: {"ok": False, "message": "refresh timeout"})
@@ -248,11 +249,15 @@ def test_install_job_measures_configured_runtime(monkeypatch, tmp_path, backend,
return None
return str(standard) if binary == backend else binary
- def probe(binary):
- probed.append(binary)
+ def observe(binary, _backend):
+ path = resolve(binary)
+ if path is None:
+ return api.CliHealth(False, None, "missing").payload()
+ probed.append(path)
if change == ("unknown-after" if installed else "unknown-before"):
- return None
- return "1.0.1" if installed and change == "version" else "1.0.0"
+ return api.CliHealth(True, path, "broken", reason="invalid_version").payload()
+ version = "1.0.1" if installed and change == "version" else "1.0.0"
+ return api.CliHealth(True, path, "ok", version).payload()
class InstallProcess:
returncode = 0
@@ -269,8 +274,7 @@ def test_install_job_measures_configured_runtime(monkeypatch, tmp_path, backend,
return "fixture installed", ""
monkeypatch.setattr(api, "resolve_cli_path", resolve)
- monkeypatch.setattr(api, "_probe_cli_version", probe)
- monkeypatch.setattr(api, "_cached_version", Mock(side_effect=AssertionError("must measure, not use cached versions")))
+ monkeypatch.setattr(api, "detect_cli", observe)
monkeypatch.setattr(api.subprocess, "Popen", InstallProcess)
monkeypatch.setattr(
api, "install_agent",
@@ -283,10 +287,15 @@ def test_install_job_measures_configured_runtime(monkeypatch, tmp_path, backend,
started = api.start_agent_install_job(backend)
result = _wait_for_install_job(started["job_id"])
+ if change == "unknown-after":
+ assert result["status"] == "failed" and result["code"] == "cli_readback_failed"
+ refresh.assert_not_called()
+ return
assert result["status"] == "succeeded"
assert result["ok"] is True
assert getattr(V2Config.load().agents, backend).cli_path == str(standard)
- assert resolved == [str(configured), backend, str(standard)]
+ assert resolved[0] == str(configured) and resolved[-1] == str(standard)
+ assert backend in resolved and set(resolved) <= {str(configured), backend, str(standard)}
assert probed == ([str(standard)] if change == "fresh-install" else [str(configured), str(standard)])
if change == "unchanged":
refresh.assert_not_called()
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index 40c48dc68..6638b0bc8 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -860,7 +860,7 @@ def test_doctor_surfaces_configuration_recovery_warnings(monkeypatch, tmp_path):
monkeypatch.setattr(cli, "_managed_dependencies_doctor_items", lambda **_kwargs: [])
monkeypatch.setattr(cli, "_show_runtime_doctor_items", lambda **_kwargs: [])
monkeypatch.setattr(cli, "_local_cli_installation_items", lambda: [])
- monkeypatch.setattr(cli.api, "detect_cli", lambda _path: {})
+ monkeypatch.setattr(cli.api, "detect_cli", lambda _path, _backend: {"found": False, "path": None, "status": "missing"})
result = cli._doctor()
diff --git a/ui/e2e/badge-triggers/badges.spec.ts b/ui/e2e/badge-triggers/badges.spec.ts
index dab67f3fe..ee6f46cb2 100644
--- a/ui/e2e/badge-triggers/badges.spec.ts
+++ b/ui/e2e/badge-triggers/badges.spec.ts
@@ -15,8 +15,9 @@ for (const locale of ['en', 'zh'] as const) {
await page.route('**/api/version', (route) => route.fulfill({ json: {
current: '3.1.4', latest: '3.1.5', has_update: true,
} }));
- await page.route('**/api/backend/codex/runtime', (route) => route.fulfill({ json: {
- installed: true, version: '1.0.0', latest_version: '1.1.0',
+ await page.route('**/api/backend/codex/runtime?cli_path=*', (route) => route.fulfill({ json: {
+ installed: true, status: 'ok', cli_path: 'codex', resolved_path: 'codex',
+ current_version: '1.0.0', version: '1.0.0', latest_version: '1.1.0',
has_update: new URL(page.url()).searchParams.get('state') === 'update',
} }));
});
diff --git a/ui/e2e/onboarding-fidelity/support.ts b/ui/e2e/onboarding-fidelity/support.ts
index 39d785e4d..4a0c3e316 100644
--- a/ui/e2e/onboarding-fidelity/support.ts
+++ b/ui/e2e/onboarding-fidelity/support.ts
@@ -100,7 +100,7 @@ export async function serveProduct(page: Page) {
// The setup step reads each assistant's runtime and OpenCode's permission flag. They
// are answered as an installed, permitted runtime so the screen renders the state the
// design describes rather than the error state a missing backend would produce.
- await page.route('**/api/backend/*/runtime', (route) => {
+ await page.route('**/api/backend/*/runtime*', (route) => {
const name = new URL(route.request().url()).pathname.split('/').at(-2);
return route.fulfill({
json: {
@@ -110,6 +110,7 @@ export async function serveProduct(page: Page) {
cli_path: name,
resolved_path: `/fixture/bin/${name}`,
installed: true,
+ status: 'ok',
current_version: '1.0.0',
latest_version: '1.0.0',
has_update: false,
diff --git a/ui/e2e/workbench-general/setup-handoff.spec.ts b/ui/e2e/workbench-general/setup-handoff.spec.ts
index cda507cc2..d8977d7ea 100644
--- a/ui/e2e/workbench-general/setup-handoff.spec.ts
+++ b/ui/e2e/workbench-general/setup-handoff.spec.ts
@@ -2,6 +2,7 @@ import { expect, test } from '@playwright/test';
import type { Page } from '@playwright/test';
import { DESKTOP, config, open, serveProduct } from './support';
+import { CONTRACT_VERSION } from '../../src/components/settings/models/types';
/**
* The handoff the wizard makes to the home, driven end to end through the real
@@ -22,23 +23,22 @@ import { DESKTOP, config, open, serveProduct } from './support';
* waved off.
*
* Hermetic like the rest of the suite: every request is answered or refused by
- * `serveProduct`, nothing reaches a running service, and the one write the flow
- * makes (setup completion) is answered from the same fixture instance the reads
- * come from. Each test asserts nothing was refused.
+ * `serveProduct`, nothing reaches a running service, and the two config writes
+ * the flow makes (the provider bootstrap seed and setup completion) are answered
+ * from the same stateful fixture instance. Each test asserts nothing was refused.
*/
const COMPOSER = 'Tell the agent what you want…';
const DRAFT = '整理一下这周的发布说明';
/**
- * One installed, connected assistant and two that are neither. The home's
- * default Agent runs on Codex, so Codex is the only backend that can
- * corroborate anything here — and a fixture where all three were ready could
- * not tell "asked about the right one" from "asked about any of them".
+ * One installed, connected assistant and one applied bootstrap assistant. The home's
+ * default Agent runs on Codex, so Codex is the only backend that can corroborate
+ * anything here — and the Hub supply fixture below still makes its route explicit.
*/
const CONNECTIONS: Record<string, Record<string, unknown>> = {
codex: { installed: true, enabled: true, auth: 'api_key', application: 'applied', ready: true, entry_eligible: true },
- claude: { installed: false, enabled: false, auth: 'none', application: 'stopped', ready: false, entry_eligible: false },
+ claude: { installed: true, enabled: true, auth: 'api_key', application: 'applied', ready: true, entry_eligible: true },
opencode: { installed: false, enabled: false, auth: 'none', application: 'stopped', ready: false, entry_eligible: false },
};
@@ -52,6 +52,66 @@ const CONNECTIONS: Record<string, Record<string, unknown>> = {
*/
const AGENT_MODEL = 'gpt-5';
const PICKED_MODEL = 'gpt-5-codex';
+const HUB_SOURCE_ID = 'source-openai-fixture';
+
+const HUB_SOURCE = {
+ id: HUB_SOURCE_ID,
+ vendor: 'openai',
+ kind: 'api_key',
+ display_name: 'OpenAI',
+ protocol: 'openai_chat',
+ base_url: null,
+ supply_channel: 'hub',
+ billing: 'metered',
+ state: { status: 'active', retry_at: null, detail_key: null },
+ models: [{
+ id: AGENT_MODEL,
+ display_name: 'GPT-5',
+ origin: 'discovered',
+ reasoning_efforts: [],
+ reasoning_efforts_source: null,
+ }],
+ last_discovered_at: '2026-01-01T00:00:00Z',
+};
+
+const HUB_CODEX_SUPPLY = {
+ backend: 'codex',
+ cli_present: true,
+ mode: 'hub',
+ menu_kind: 'fixed',
+ sources: {
+ order: [HUB_SOURCE_ID],
+ eligibility: [{
+ source_id: HUB_SOURCE_ID,
+ eligible: true,
+ reason_key: null,
+ in_current_model_chain: true,
+ process_availability_reason: null,
+ }],
+ },
+ routes: {},
+ builtin_models: [],
+ catalog_models: [],
+ menu: null,
+ model_supply: [{ model_id: AGENT_MODEL, route_origin: 'automatic', chain_length: 1, has_runnable_hop: true }],
+ named_agents: [{ name: 'codex', effective_model_id: AGENT_MODEL, supply_status: 'ok', route_reason: null }],
+ supply_status: 'ok',
+};
+
+const FULL_AGENTS = {
+ codex: {
+ id: 'agent-codex', name: 'codex', display_name: 'Codex', description: null,
+ backend: 'codex', model: AGENT_MODEL, reasoning_effort: null, enabled: true,
+ archived: false, archived_at: null, source: 'builtin', updated_at: '2026-01-01T00:00:00Z',
+ system_prompt: null, metadata: { builtin_default: true }, created_at: '2026-01-01T00:00:00Z',
+ },
+ claude: {
+ id: 'agent-claude', name: 'claude', display_name: 'Claude Code', description: null,
+ backend: 'claude', model: null, reasoning_effort: null, enabled: true,
+ archived: false, archived_at: null, source: 'builtin', updated_at: '2026-01-01T00:00:00Z',
+ system_prompt: null, metadata: { builtin_default: true }, created_at: '2026-01-01T00:00:00Z',
+ },
+} as const;
const backendOf = (url: string) => new URL(url).pathname.split('/').at(-2) ?? '';
@@ -61,7 +121,7 @@ const backendOf = (url: string) => new URL(url).pathname.split('/').at(-2) ?? ''
* Connection reads answer at once until setup is persisted; every read AFTER
* that is the home's own — the wizard is gone by then — and is held until the
* test lets it answer. That boundary is the product's, not the harness's: the
- * completion write is exactly what separates the two.
+ * completion write is what separates the setup-owned reads from the home's post-handoff reads.
*/
const withSetupApi = async (page: Page) => {
const homeReads: string[] = [];
@@ -78,11 +138,12 @@ const withSetupApi = async (page: Page) => {
}
await route.fulfill({ json: { ok: true, backend, ...CONNECTIONS[backend] } });
});
- await page.route('**/api/backend/*/runtime', (route) => {
+ await page.route('**/api/backend/*/runtime*', (route) => {
const backend = backendOf(route.request().url());
return route.fulfill({
json: {
ok: true,
+ status: CONNECTIONS[backend]?.installed ? 'ok' : 'missing',
name: backend,
enabled: Boolean(CONNECTIONS[backend]?.enabled),
cli_path: backend,
@@ -97,20 +158,43 @@ const withSetupApi = async (page: Page) => {
});
});
await page.route('**/api/opencode/permission-status', (route) => route.fulfill({ json: { ok: true, permission_allowed: true } }));
- // The Agent catalog with a model on the default Agent, and the model list its
- // backend answers with — the product's own two reads for this, not a new
- // contract. Stated here rather than in the shared harness: the capture specs
- // assert against that fixture, and this is the one test about the model field.
- await page.route('**/api/agents**', (route) => route.fulfill({
+ await page.route('**/api/models/sources', (route) => route.fulfill({ json: { ok: true, sources: [HUB_SOURCE] } }));
+ await page.route('**/api/models/migration/scan', (route) => route.fulfill({ json: { ok: true, scan: { items: [] } } }));
+ await page.route('**/api/models/runtime/status', (route) => route.fulfill({
json: {
ok: true,
- agents: [
- { id: 'agent-codex', name: 'codex', backend: 'codex', enabled: true, model: AGENT_MODEL },
- { id: 'agent-claude', name: 'claude', backend: 'claude', enabled: true },
- ],
- default_agent_name: 'codex',
+ runtime: {
+ contract_version: CONTRACT_VERSION,
+ enabled: true,
+ host_platform: 'linux',
+ manifest: { name: 'cliproxyapi', resolution: 'resolved', version: 'fixture', source_sha: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', assets: [] },
+ status: { installed_version: 'fixture', verified: true, health: 'ok' },
+ },
},
}));
+ await page.route('**/api/models/agents**', (route) => route.fulfill({ json: { ok: true, agents: [HUB_CODEX_SUPPLY] } }));
+ // Preserve the existing brief catalog response while answering the uncached full
+ // records that setup reads to identify its builtin targets.
+ await page.route('**/api/agents**', (route) => {
+ const path = new URL(route.request().url()).pathname;
+ if (path.startsWith('/api/agents/')) {
+ const name = path.split('/').at(-1) ?? '';
+ const agent = FULL_AGENTS[name as keyof typeof FULL_AGENTS];
+ return route.fulfill({ json: agent
+ ? { ok: true, default_agent_name: 'codex', agent }
+ : { ok: false, agent: null, default_agent_name: 'codex' } });
+ }
+ return route.fulfill({
+ json: {
+ ok: true,
+ agents: [
+ { id: 'agent-codex', name: 'codex', backend: 'codex', enabled: true, model: AGENT_MODEL },
+ { id: 'agent-claude', name: 'claude', backend: 'claude', enabled: true },
+ ],
+ default_agent_name: 'codex',
+ },
+ });
+ });
await page.route('**/api/codex/models', (route) => route.fulfill({
json: { ok: true, models: [AGENT_MODEL, PICKED_MODEL] },
}));
@@ -121,15 +205,16 @@ const withSetupApi = async (page: Page) => {
json: CONNECTIONS[name]?.installed ? { found: true, path: `/fixture/bin/${name}` } : { found: false },
});
});
- // The ONE write this flow makes. Answering it here rather than letting the
- // harness refuse it is what makes the completion real — and what it answers
- // with is the same instance every read comes from.
+ // The two config writes this flow makes: the provider bootstrap seed is not
+ // completion, and only the actual completion write changes the readback state.
await page.route('**/api/config', async (route) => {
const request = route.request();
+ if (request.method() === 'GET') return route.fulfill({ json: { ...config('en'), setup_completed: completed } });
if (request.method() !== 'POST') return route.fallback();
- writes.push(request.postDataJSON());
- completed = true;
- return route.fulfill({ json: { ...config('en'), setup_completed: true } });
+ const payload = request.postDataJSON();
+ writes.push(payload);
+ if (payload?.setup_completed === true) completed = true;
+ return route.fulfill({ json: { ...config('en'), setup_completed: completed } });
});
return { homeReads, writes, release: () => release() };
@@ -154,9 +239,11 @@ const expectDefaultModel = async (page: Page) => {
/** Walks the real wizard to the point where entering is the user's to do. */
async function reachEntry(page: Page) {
await open(page, '/setup');
- await page.getByRole('button', { name: 'Get started' }).click();
- await expect(page.getByRole('heading', { name: 'Connect AI. Get to work' })).toBeVisible();
- const enter = page.getByRole('button', { name: 'Enter workspace' });
+ await page.getByRole('button', { name: 'Get started', exact: true }).click();
+ await expect(page.getByRole('heading', { name: 'Add model providers', exact: true })).toBeVisible();
+ await page.getByRole('button', { name: 'Continue to assistants', exact: true }).click();
+ await expect(page.getByRole('heading', { name: 'Choose your AI assistants', exact: true })).toBeVisible();
+ const enter = page.getByRole('button', { name: 'Enter workspace', exact: true });
await expect(enter).toBeEnabled();
return enter;
}
@@ -174,7 +261,7 @@ test.describe('Setup handoff to the Workbench home', () => {
// The home, reached by the wizard's own navigation.
await expect(page).toHaveURL(/127\.0\.0\.1:5213\/$/);
await expect(heroTitle(page)).toBeVisible();
- expect(setup.writes).toEqual([{ setup_completed: true }]);
+ expect(setup.writes).toEqual([{}, { setup_completed: true }]);
// The home asked the backend its Agent route actually runs — and nothing
// else. While that read is open there is nothing corroborated, so the
@@ -200,12 +287,12 @@ test.describe('Setup handoff to the Workbench home', () => {
// The Agent the setup left selected is the one the home offers, the model
// the user picked is untouched by the announcement arriving over it, and
- // setup completion did not rewrite either: the completion write is still
- // the only one this flow has made.
+ // setup completion did not rewrite either: the bootstrap seed and completion
+ // remain the only two config writes this flow has made.
await expect(agentTrigger(page)).toHaveText(/codex/);
await expect(agentTrigger(page)).toContainText(PICKED_MODEL);
await expect(projectChip(page)).toHaveClass(/bg-mint-soft/);
- expect(setup.writes).toEqual([{ setup_completed: true }]);
+ expect(setup.writes).toEqual([{}, { setup_completed: true }]);
// Dismissing is about the banner and nothing else: the home the user has
// already started using is untouched.
@@ -229,9 +316,9 @@ test.describe('Setup handoff to the Workbench home', () => {
expect(setup.homeReads).toHaveLength(readsBeforeReload);
// And the model pick was a pick for this composer, never a write: the new
// page inherits the Agent's own default again, which is the same reason the
- // completion write is still the only request this flow has sent.
+ // The bootstrap seed and completion remain the only two config writes this flow has sent.
await expectDefaultModel(page);
- expect(setup.writes).toEqual([{ setup_completed: true }]);
+ expect(setup.writes).toEqual([{}, { setup_completed: true }]);
expect(denied).toEqual([]);
});
diff --git a/ui/e2e/workbench-general/support.ts b/ui/e2e/workbench-general/support.ts
index e6ab87cdf..c536a839c 100644
--- a/ui/e2e/workbench-general/support.ts
+++ b/ui/e2e/workbench-general/support.ts
@@ -27,9 +27,14 @@ const SESSION = {
* answers a WRITE to `/api/config` can answer with the same instance it reads,
* rather than describing a second one. */
export const config = (language: Lang) => ({
+ version: 'v2',
+ setup_completed: false,
+ capabilities: { model_hub: { enabled: true } },
+ model_hub: { enabled: true },
mode: 'local',
setup_state: { needs_setup: false },
- platforms: { enabled: [] },
+ platforms: { primary: 'slack', enabled: [] },
+ runtime: {},
agents: {
codex: { enabled: true, cli_path: 'codex' },
claude: { enabled: true, cli_path: 'claude' },
diff --git a/ui/eslint-baseline.json b/ui/eslint-baseline.json
index 227ecbc6e..0cab9683a 100644
--- a/ui/eslint-baseline.json
+++ b/ui/eslint-baseline.json
@@ -101,7 +101,7 @@
"@typescript-eslint/no-explicit-any": 1
},
"src/context/ApiContext.tsx": {
- "@typescript-eslint/no-explicit-any": 49,
+ "@typescript-eslint/no-explicit-any": 48,
"react-refresh/only-export-components": 1
},
"src/context/DockProvider.tsx": {
diff --git a/ui/src/components/Wizard.tsx b/ui/src/components/Wizard.tsx
index 4ce916285..73ec7e5b4 100644
--- a/ui/src/components/Wizard.tsx
+++ b/ui/src/components/Wizard.tsx
@@ -375,7 +375,7 @@ export function Wizard() {
agentReads: setupAgentReads,
getRuntimeStatus: () => modelsApi.getRuntimeStatus(),
getVibeAgent: (name, params) => api.getVibeAgent(name, { ...params, cache: false }),
- detectCli: (binary) => api.detectCli(binary),
+ detectCli: (binary, backend) => api.detectCli(binary, backend),
}), [api, setupAgentReads]);
const retrySetup = useCallback(() => {
// Order matters only in what it means: re-read the configuration, and let the
diff --git a/ui/src/components/onboarding/AssistantRow.tsx b/ui/src/components/onboarding/AssistantRow.tsx
index ba01ae82c..5c3a0368f 100644
--- a/ui/src/components/onboarding/AssistantRow.tsx
+++ b/ui/src/components/onboarding/AssistantRow.tsx
@@ -1,4 +1,5 @@
import type { ReactNode } from 'react';
+import type { CliStatus } from '@/context/ApiContext';
import { Check, ChevronRight, Download, KeyRound, RefreshCw, Settings, SlidersHorizontal } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { BackendIcon } from '../visual';
@@ -16,7 +17,7 @@ export type AssistantRouteView =
export interface AssistantRowProps {
backend: AssistantId;
- status: 'unknown' | 'ok' | 'missing';
+ status: CliStatus;
installing: boolean;
detecting: boolean;
error?: { message: string; hint?: string | null; output?: string | null; exit_code?: number };
@@ -147,6 +148,10 @@ export function AssistantRow({ backend, status, installing, detecting, error, li
<Badge variant="secondary"><RefreshCw size={12} className={installing || detecting ? 'motion-safe:animate-spin' : ''} />
{t(installing ? 'agentDetection.installing' : detecting ? 'onboarding.welcome.detecting' : 'common.notChecked')}
</Badge>
+ ) : status === 'broken' ? (
+ <Badge variant="destructive"><span className="size-2 rounded-full bg-current" />
+ {t('backendLifecycle.statusBroken')}
+ </Badge>
) : status === 'ok' ? lifecycle : (
<Badge variant={error ? 'destructive' : 'secondary'}><span className="size-2 rounded-full bg-current" />
{t(error ? 'onboarding.setup.installFailed' : 'onboarding.setup.notInstalled')}
@@ -180,7 +185,8 @@ export function AssistantRow({ backend, status, installing, detecting, error, li
<summary>{t('onboarding.setup.permissionFailed')}</summary>{permission.error}
</details>
) : <p className="onboarding-assistant-note">
- {permissionNeeded ? t('onboarding.setup.notePermission', { name: label }) : hubState
+ {status === 'broken' ? t('backendLifecycle.brokenHint', { name: label })
+ : permissionNeeded ? t('onboarding.setup.notePermission', { name: label }) : hubState
? t(hubState === 'missing' ? 'onboarding.setup.noteNotInstalled'
: hubState === 'enabled' || hubState === 'idle'
? (route?.kind === 'no-agent-model' ? 'onboarding.setup.noteModelUnset'
@@ -203,7 +209,11 @@ export function AssistantRow({ backend, status, installing, detecting, error, li
{t('onboarding.setup.allowToolCalls')}
</Button>
)}
- {hubState === 'checking' ? null : hubState === 'missing' ? (
+ {status === 'broken' ? (
+ <Button type="button" variant="secondary" className="onboarding-method-row" onClick={onInstall} disabled={installing || detecting}>
+ <Download size={16} />{t('backendLifecycle.reinstall')}
+ </Button>
+ ) : hubState === 'checking' ? null : hubState === 'missing' ? (
<Button type="button" variant="secondary" className="onboarding-method-row" onClick={onInstall} disabled={installing || detecting}>
{installing ? <RefreshCw size={16} className="motion-safe:animate-spin" /> : <Download size={16} />}
{t(installing ? 'agentDetection.installing' : error ? 'common.retry' : 'onboarding.setup.installAndEnable')}
diff --git a/ui/src/components/onboarding/AssistantSetup.test.tsx b/ui/src/components/onboarding/AssistantSetup.test.tsx
index 8a638df35..9bc387d1c 100644
--- a/ui/src/components/onboarding/AssistantSetup.test.tsx
+++ b/ui/src/components/onboarding/AssistantSetup.test.tsx
@@ -76,8 +76,8 @@ beforeEach(() => {
mock.api.getClaudeAuth.mockResolvedValue({ ok: true, active_auth_mode: 'none' });
mock.api.getCodexAuth.mockResolvedValue({ ok: true, active_auth_mode: 'none' });
mock.api.getOpencodeProviders.mockResolvedValue({ ok: true, providers: [] });
- mock.api.detectCli.mockResolvedValue({ found: true, path: '/isolated/bin/assistant' });
- mock.api.getBackendRuntime.mockResolvedValue({ installed: true, has_update: false });
+ mock.api.detectCli.mockResolvedValue({ found: true, status: 'ok' as const, path: '/isolated/bin/assistant' });
+ mock.api.getBackendRuntime.mockImplementation(async (_name, cliPath) => ({ ok: true, installed: true, status: 'ok', cli_path: cliPath, resolved_path: cliPath, has_update: false }));
mock.api.listVibeAgents.mockResolvedValue({ ok: true, agents: [], default_agent_name: null });
mock.api.getVibeAgent.mockResolvedValue({ ok: false, agent: null });
mock.models.listSources.mockResolvedValue([]);
@@ -170,7 +170,7 @@ describe('assistant installation presentation', () => {
it('does not enable from a stale Hub read when reentry offered ordinary Install', async () => {
const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
saved.agents.claude.enabled = false;
- mock.api.detectCli.mockResolvedValue({ found: false, path: '' });
+ mock.api.detectCli.mockResolvedValue({ found: false, status: 'missing' as const, path: '' });
mock.api.getBackendConnection.mockImplementation(async (backend) => ({
ok: true, backend, installed: false, enabled: false, auth: 'none',
application: 'applied', ready: false, entry_eligible: false, supply_mode: 'hub',
@@ -200,7 +200,7 @@ describe('assistant installation presentation', () => {
it('does not promise enablement when a missing assistant has conflicting Hub and Direct reads', async () => {
const saved = { ...data(), capabilities: { model_hub: { enabled: true } } };
saved.agents.claude.enabled = false;
- mock.api.detectCli.mockResolvedValue({ found: false, path: '' });
+ mock.api.detectCli.mockResolvedValue({ found: false, status: 'missing' as const, path: '' });
mock.api.getBackendConnection.mockImplementation(async (backend) => ({
ok: true, backend, installed: false, enabled: false, auth: 'none',
application: 'applied', ready: false, entry_eligible: false, supply_mode: 'hub',
@@ -250,7 +250,7 @@ describe('assistant installation presentation', () => {
mock.api.installAgent.mockResolvedValue({ ok: true, path: '/isolated/bin/claude' });
fireEvent.click(row('Claude Code').getByRole('button', { name: 'Retry' }));
await waitFor(() => expect(row('Claude Code').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy());
- expect(mock.api.detectCli).toHaveBeenCalledWith('/isolated/bin/claude');
+ expect(mock.api.detectCli).toHaveBeenCalledWith('/isolated/bin/claude', 'claude');
expect(row('Codex').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy();
});
it('does not undo a newer disable when an install finishes', async () => {
@@ -395,7 +395,7 @@ describe('assistant installation presentation', () => {
});
it('an available update keeps Continue and configuration usable', async () => {
const saved = data(); saved.agents.claude.status = 'ok';
- mock.api.getBackendRuntime.mockResolvedValue({ installed: true, has_update: true, current_version: '1', latest_version: '2' });
+ mock.api.getBackendRuntime.mockImplementation(async (_name, path) => ({ installed: true, status: 'ok', cli_path: path, resolved_path: path, has_update: true, current_version: '1', latest_version: '2' }));
const next = vi.fn();
render(wrap(<AgentDetection data={saved} onNext={next} />));
await screen.findByRole('button', { name: en.backendLifecycle.statusUpdateAvailable });
@@ -406,7 +406,7 @@ describe('assistant installation presentation', () => {
});
it('keeps a failed upgrade from the state row on the card with its reason and output', async () => {
const saved = data(); saved.agents.codex.status = 'ok';
- mock.api.getBackendRuntime.mockResolvedValue({ installed: true, has_update: true, current_version: '1', latest_version: '2' });
+ mock.api.getBackendRuntime.mockImplementation(async (_name, path) => ({ installed: true, status: 'ok', cli_path: path, resolved_path: path, has_update: true, current_version: '1', latest_version: '2' }));
const failure = {
ok: false, message: 'Could not upgrade Codex.', code: 'npm_leftover_directory', exit_code: 190,
hint: 'npm left a temporary folder behind from an earlier interrupted update: /usr/local/lib/node_modules/@openai/.codex-lD3lp9Ti. Delete that folder, then try again.',
@@ -428,10 +428,10 @@ describe('assistant installation presentation', () => {
});
it('re-detects a CLI a failed upgrade from the state row removed, keeping the reason', async () => {
const saved = data(); saved.agents.codex.status = 'ok';
- mock.api.getBackendRuntime.mockResolvedValue({ installed: true, has_update: true, current_version: '1', latest_version: '2' });
+ mock.api.getBackendRuntime.mockImplementation(async (_name, path) => ({ installed: true, status: 'ok', cli_path: path, resolved_path: path, has_update: true, current_version: '1', latest_version: '2' }));
mock.api.installAgent.mockImplementation(async () => {
- mock.api.detectCli.mockResolvedValue({ found: false, path: null });
- mock.api.getBackendRuntime.mockResolvedValue({ installed: false, has_update: false, resolved_path: null });
+ mock.api.detectCli.mockResolvedValue({ found: false, status: 'missing' as const, path: null });
+ mock.api.getBackendRuntime.mockImplementation(async (_name, path) => ({ installed: false, status: 'missing', cli_path: path, has_update: false, resolved_path: null }));
return { ok: false, message: 'Could not upgrade Codex.', output: 'npm error code ENOTEMPTY' };
});
render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
@@ -445,9 +445,9 @@ describe('assistant installation presentation', () => {
it('holds the state row until the chip reads an upgrade back, then offers it again if still behind', async () => {
const path = '/isolated/bin/codex';
const saved = data(); saved.agents.codex.status = 'ok'; saved.agents.codex.cli_path = path;
- const behind = { installed: true, has_update: true, current_version: '1', latest_version: '2', resolved_path: path };
+ const behind = { installed: true, status: 'ok' as const, cli_path: path, has_update: true, current_version: '1', latest_version: '2', resolved_path: path };
mock.api.getBackendRuntime.mockResolvedValue(behind);
- mock.api.detectCli.mockResolvedValue({ found: true, path });
+ mock.api.detectCli.mockResolvedValue({ found: true, status: 'ok' as const, path });
let readBack!: (runtime: typeof behind) => void;
mock.api.installAgent.mockImplementation(async () => {
// A native updater can exit zero without moving the version.
@@ -500,9 +500,9 @@ describe('assistant installation presentation', () => {
fireEvent.keyDown(await screen.findByRole('dialog'), { key: 'Escape' });
expect(screen.getByRole('button', { name: 'Back' }).hasAttribute('disabled')).toBe(true);
await act(async () => finishConfig({ agents: { claude: { enabled: true, cli_path: '/isolated/新的路径/claude' } } }));
- expect(mock.api.detectCli).toHaveBeenCalledWith('/isolated/新的路径/claude');
+ expect(mock.api.detectCli).toHaveBeenCalledWith('/isolated/新的路径/claude', 'claude');
expect(screen.getByRole('button', { name: 'Back' }).hasAttribute('disabled')).toBe(true);
- await act(async () => finishDetection({ found: true, path: '/isolated/真实路径/claude' }));
+ await act(async () => finishDetection({ found: true, status: 'ok' as const, path: '/isolated/真实路径/claude' }));
fireEvent.click(screen.getByRole('button', { name: 'Back' }));
expect(back).toHaveBeenCalledWith({ agents: expect.objectContaining({ claude: expect.objectContaining({ cli_path: '/isolated/真实路径/claude', status: 'ok' }) }) });
});
@@ -514,8 +514,8 @@ describe('assistant installation presentation', () => {
}
await waitFor(() => expect(screen.getAllByRole('alert')).toHaveLength(3));
mock.api.detectCli.mockImplementation((name) => name === 'claude'
- ? Promise.resolve({ found: true, path: '/isolated/external/claude' })
- : name === 'codex' ? Promise.resolve({ found: false }) : Promise.reject(new Error('Probe unavailable')));
+ ? Promise.resolve({ found: true, status: 'ok' as const, path: '/isolated/external/claude' })
+ : name === 'codex' ? Promise.resolve({ found: false, status: 'missing' as const }) : Promise.reject(new Error('Probe unavailable')));
fireEvent.click(screen.getByRole('button', { name: en.agentDetection.rescan }));
await waitFor(() => expect(row('Claude Code').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy());
expect(row('Claude Code').queryByRole('alert')).toBeNull();
@@ -525,7 +525,7 @@ describe('assistant installation presentation', () => {
expect(row('OpenCode').getByText('Error: Probe unavailable')).toBeTruthy();
expect(row('OpenCode').queryByRole('button', { name: en.onboarding.setup.enabled })).toBeNull();
// A rejected probe retains install evidence; a later missing result shows it again.
- mock.api.detectCli.mockResolvedValue({ found: false });
+ mock.api.detectCli.mockResolvedValue({ found: false, status: 'missing' as const });
fireEvent.click(row('OpenCode').getByRole('button', { name: 'Retry' }));
await waitFor(() => expect(row('OpenCode').getByText('Failed opencode')).toBeTruthy());
expect(row('OpenCode').getByText('Details opencode')).toBeTruthy();
@@ -617,7 +617,7 @@ describe('assistant installation presentation', () => {
// Only the retained path resolves, so a probe that fell back to the snapshot is
// visible twice over: in the call log, and as a backend reported missing again.
mock.api.detectCli.mockImplementation((binary: string) => Promise.resolve(
- binary === '/retained/claude' ? { found: true, path: '/retained/claude' } : { found: false }));
+ binary === '/retained/claude' ? { found: true, status: 'ok' as const, path: '/retained/claude' } : { found: false, status: 'missing' as const }));
mock.api.installAgent.mockResolvedValue({ ok: true, path: '/retained/claude', message: '' });
const probes = (binary: string) => mock.api.detectCli.mock.calls.filter(([called]) => called === binary).length;
const publish = vi.fn();
@@ -1359,7 +1359,7 @@ describe('settled wizard enablement follows persistence and latest intent', () =
const oldRead = pending<ReturnType<typeof stateFor>>();
mock.api.getBackendConnection.mockImplementation((name) => name === 'claude' ? oldRead.promise : Promise.resolve(stateFor(name)));
fireEvent.click(screen.getByRole('button', { name: en.agentDetection.rescan }));
- await waitFor(() => expect(mock.api.detectCli).toHaveBeenCalledWith('claude'));
+ await waitFor(() => expect(mock.api.detectCli).toHaveBeenCalledWith('claude', 'claude'));
const off = pending<unknown>(); const on = pending<unknown>();
mock.api.mutateConfig.mockReturnValueOnce(off.promise).mockReturnValueOnce(on.promise);
fireEvent.click(checkbox); fireEvent.click(checkbox);
@@ -1388,7 +1388,7 @@ describe('settled wizard enablement follows persistence and latest intent', () =
const early = pending<ReturnType<typeof stateFor>>();
mock.api.getBackendConnection.mockImplementation((name) => name === 'claude' ? early.promise : Promise.resolve(stateFor(name)));
fireEvent.click(screen.getByRole('button', { name: en.agentDetection.rescan }));
- await waitFor(() => expect(mock.api.detectCli).toHaveBeenCalledWith('claude'));
+ await waitFor(() => expect(mock.api.detectCli).toHaveBeenCalledWith('claude', 'claude'));
mock.api.getBackendConnection.mockImplementation(async (name) => stateFor(name));
await failedToggle(checkbox);
await act(async () => early.resolve(stateFor('claude')));
diff --git a/ui/src/components/onboarding/BackendConnection.test.tsx b/ui/src/components/onboarding/BackendConnection.test.tsx
index 71f449c83..0144c0106 100644
--- a/ui/src/components/onboarding/BackendConnection.test.tsx
+++ b/ui/src/components/onboarding/BackendConnection.test.tsx
@@ -55,8 +55,8 @@ beforeEach(() => {
mock.api.saveClaudeAuth.mockResolvedValue({ ok: true, restart: { ok: true } });
mock.api.cancelOAuthWeb.mockResolvedValue({ ok: true });
mock.api.getConfig.mockResolvedValue({ agents: { claude: { enabled: false, cli_path: 'claude' }, codex: { enabled: false, cli_path: 'codex' } } });
- mock.api.detectCli.mockImplementation(async (binary) => ({ found: true, path: binary }));
- mock.api.getBackendRuntime.mockImplementation(async (backend) => ({ ok: true, name: backend, enabled: true, installed: true, process_status: 'running' }));
+ mock.api.detectCli.mockImplementation(async (binary) => ({ found: true, status: 'ok' as const, path: binary }));
+ mock.api.getBackendRuntime.mockImplementation(async (backend, path) => ({ ok: true, name: backend, cli_path: path, resolved_path: path, status: 'ok', enabled: true, installed: true, process_status: 'running' }));
mock.api.claudeModels.mockResolvedValue({ ok: true, models: [] });
mock.api.codexModels.mockResolvedValue({ ok: true, models: [] });
});
@@ -266,7 +266,7 @@ describe('shared Settings and onboarding connection owner', () => {
expect(mock.api.getBackendConnection).toHaveBeenCalledWith(backend);
});
it.each(['applied', 'failed', 'unreadable'] as const)(`${backend} Settings restart settlement reads fresh auth/application (%s)`, async (outcome) => {
- mock.api.getBackendRuntime.mockResolvedValue({ ok: true, name: backend, enabled: true, installed: true, supports_restart: true, process_status: 'running' });
+ mock.api.getBackendRuntime.mockImplementation(async (_backend, path) => ({ ok: true, name: backend, cli_path: path, resolved_path: path, status: 'ok', enabled: true, installed: true, supports_restart: true, process_status: 'running' }));
await mountParent();
const form = within(document.querySelector('.backend-connection-form') as HTMLElement);
fireEvent.change(form.getByLabelText(en.onboarding.connection.baseUrl), { target: { value: 'https://draft.invalid' } });
@@ -440,12 +440,12 @@ describe('shared Settings and onboarding connection owner', () => {
mock.api.getConfig.mockResolvedValue({ agents: { codex: { enabled: true, cli_path: 'codex' } } });
render(wrap(<CodexProviderConfig />));
await screen.findByText(en.onboarding.connection.connected);
- const detected = deferred<{ found: boolean; path: string }>();
+ const detected = deferred<{ found: boolean; path: string; status: 'ok' }>();
mock.api.detectCli.mockReturnValue(detected.promise);
fireEvent.click(screen.getByRole('button', { name: en.common.detect }));
const input = screen.getByLabelText(en.agentDetection.cliPath) as HTMLInputElement;
fireEvent.change(input, { target: { value: '/fixture/newer-path' } });
- await act(async () => detected.resolve({ found: true, path: '/fixture/older-probe' }));
+ await act(async () => detected.resolve({ found: true, status: 'ok' as const, path: '/fixture/older-probe' }));
expect(input.value).toBe('/fixture/newer-path');
expect(mock.api.mutateConfig).not.toHaveBeenCalled();
});
@@ -1378,8 +1378,14 @@ describe('connection dialog frame', () => {
expect(rows()).toEqual([{ title: 'OpenAI', id: 'openai' }, { title: 'Qwen', id: 'alibaba-cn' }]);
fireEvent.click(screen.getByRole('button', { name: /More providers \(2\)/ }));
- // Both stay reachable under More, under what they were configured as.
- expect(rows().slice(2)).toEqual([{ title: 'gemini', id: 'gemini' }, { title: '内部中转', id: 'dashscope' }]);
+ // Both stay reachable under More, under what they were configured as. Their
+ // display order follows the user's locale, so the identity contract is order-free.
+ const moreRows = rows().slice(2);
+ expect(moreRows).toHaveLength(2);
+ expect(moreRows).toEqual(expect.arrayContaining([
+ { title: 'gemini', id: 'gemini' },
+ { title: '内部中转', id: 'dashscope' },
+ ]));
// And they are drawn as what they are — an address you supply, the same
// mark the custom vendor has always used — not as the brand they sit next to.
const mark = (id: string) => nodes().find((node) => node.querySelector('small')?.textContent === id)
diff --git a/ui/src/components/onboarding/BuiltinAssistant.test.tsx b/ui/src/components/onboarding/BuiltinAssistant.test.tsx
index 28f77fe1f..b073748ce 100644
--- a/ui/src/components/onboarding/BuiltinAssistant.test.tsx
+++ b/ui/src/components/onboarding/BuiltinAssistant.test.tsx
@@ -84,8 +84,8 @@ beforeEach(() => {
model = null;
effort = null;
mock.api.getConfig.mockResolvedValue(data());
- mock.api.detectCli.mockResolvedValue({ found: false });
- mock.api.getBackendRuntime.mockResolvedValue({ installed: false, has_update: false });
+ mock.api.detectCli.mockResolvedValue({ found: false, status: 'missing' as const });
+ mock.api.getBackendRuntime.mockImplementation(async (_backend, path) => ({ installed: false, status: 'missing', cli_path: path, resolved_path: null, has_update: false }));
mock.api.getBackendConnection.mockImplementation(async (backend: string) => backend === 'vibey'
? { ok: true, backend, installed: true, enabled: true, auth: 'api_key', application: 'applied', ready: true, entry_eligible: true, supply_mode: 'hub' }
: { ok: true, backend, installed: false, enabled: true, auth: 'none', application: 'applied', ready: false, entry_eligible: false, supply_mode: 'hub' });
@@ -158,7 +158,8 @@ describe('the built-in assistant card', () => {
});
it('holds the whole entry on a choice that did not stand, even with a CLI assistant ready', async () => {
- mock.api.detectCli.mockResolvedValue({ found: true, path: '/isolated/bin/claude' });
+ mock.api.detectCli.mockResolvedValue({ found: true, status: 'ok' as const, path: '/isolated/bin/claude' });
+ mock.api.getBackendRuntime.mockImplementation(async (_backend, path) => ({ installed: true, status: 'ok', cli_path: path, resolved_path: path, has_update: false }));
mock.api.getBackendConnection.mockImplementation(async (backend: string) => ({
ok: true, backend, installed: true, enabled: true, auth: 'api_key', application: 'applied', ready: true, entry_eligible: true, supply_mode: 'hub',
}));
diff --git a/ui/src/components/onboarding/Welcome.test.tsx b/ui/src/components/onboarding/Welcome.test.tsx
index 79cded6af..5c937443c 100644
--- a/ui/src/components/onboarding/Welcome.test.tsx
+++ b/ui/src/components/onboarding/Welcome.test.tsx
@@ -74,7 +74,7 @@ afterEach(() => {
describe('Welcome', () => {
it('checks saved paths before advancing without persisting configuration', async () => {
- mocks.api.detectCli.mockImplementation(async (binary: string) => ({ found: binary !== 'codex', path: `/test/${binary}` }));
+ mocks.api.detectCli.mockImplementation(async (binary: string) => ({ found: binary !== 'codex', status: binary !== 'codex' ? 'ok' as const : 'missing' as const, path: `/test/${binary}` }));
const next = vi.fn();
render(wrap(<Intro data={{ agents: { claude: { cli_path: '/custom/claude' } } }} onNext={next} />));
fireEvent.click(screen.getByRole('button', { name: 'Get started' }));
@@ -83,7 +83,7 @@ describe('Welcome', () => {
expect(next.mock.calls[0][0]).toMatchObject({ __onboardingDetected: true, agents: { claude: { status: 'ok' }, codex: { status: 'missing' }, opencode: { status: 'ok' } } });
});
it('retains a failed detection on Welcome and permits retry', async () => {
- mocks.api.detectCli.mockRejectedValueOnce(new Error('Probe unavailable')).mockResolvedValue({ found: false });
+ mocks.api.detectCli.mockRejectedValueOnce(new Error('Probe unavailable')).mockResolvedValue({ found: false, status: 'missing' as const });
const next = vi.fn();
render(wrap(<Intro onNext={next} />));
fireEvent.click(screen.getByRole('button', { name: 'Get started' }));
@@ -126,7 +126,7 @@ describe('Welcome', () => {
it('refuses a detection that settles after the route went quiet, then moves when it returns', async () => {
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: false, addEventListener() {}, removeEventListener() {} })));
vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
- const probes: ((result: { found: boolean; path: string }) => void)[] = [];
+ const probes: ((result: { found: boolean; path: string; status: 'ok' }) => void)[] = [];
mocks.api.detectCli.mockImplementation(() => new Promise((resolve) => { probes.push(resolve); }));
const onward = SETUP_REGISTERED_SCREENS[1];
const shell = (routeActive: boolean) => wrap(
@@ -139,7 +139,7 @@ describe('Welcome', () => {
</RouteSurfaceActiveContext.Provider>);
const { container, rerender } = render(shell(true));
const current = () => container.querySelector('[data-setup-screen]')?.getAttribute('data-setup-screen');
- const answer = async () => act(async () => { for (const resolve of probes.splice(0)) resolve({ found: true, path: '/test/bin' }); });
+ const answer = async () => act(async () => { for (const resolve of probes.splice(0)) resolve({ found: true, status: 'ok' as const, path: '/test/bin' }); });
fireEvent.click(screen.getByRole('button', { name: 'Get started' }));
await waitFor(() => expect(probes).toHaveLength(ASSISTANT_ORDER.length));
diff --git a/ui/src/components/onboarding/WizardCompletion.test.tsx b/ui/src/components/onboarding/WizardCompletion.test.tsx
index 205da5826..604dc08a4 100644
--- a/ui/src/components/onboarding/WizardCompletion.test.tsx
+++ b/ui/src/components/onboarding/WizardCompletion.test.tsx
@@ -132,8 +132,8 @@ beforeEach(() => {
return fresh();
});
serveConfig(baseConfig());
- mock.api.detectCli.mockResolvedValue({ found: true, path: '/测试/bin/assistant' });
- mock.api.getBackendRuntime.mockResolvedValue({ installed: true, has_update: false });
+ mock.api.detectCli.mockResolvedValue({ found: true, status: 'ok' as const, path: '/测试/bin/assistant' });
+ mock.api.getBackendRuntime.mockImplementation(async (_backend, path) => ({ installed: true, status: 'ok', cli_path: path, resolved_path: path, has_update: false }));
mock.api.getBackendConnection.mockImplementation((backend) => Promise.resolve({ ok: true, backend, enabled: true, installed: true, auth: backend === 'claude' ? 'api_key' : 'none', application: running ? 'applied' : 'stopped', ready: backend === 'claude' && running, entry_eligible: backend === 'claude', permission_required: backend === 'opencode' }));
serveAgents('missing-codex', [CLAUDE_AGENT]);
mock.api.setDefaultVibeAgent.mockImplementation(async (name: string) => {
@@ -241,7 +241,7 @@ describe('the correlated entry gate', () => {
serveAgents(null, [CLAUDE_AGENT, { name: 'codex-agent', backend: 'codex', enabled: true, archived: false, source: 'builtin' }]);
mock.models.listAgents.mockResolvedValue([hubSupply('claude', []), hubSupply('codex', [route('codex-agent')])]);
const enter = await setup();
- mock.api.detectCli.mockImplementation(async (binary: string) => ({ found: binary !== 'codex', path: binary }));
+ mock.api.detectCli.mockImplementation(async (binary: string) => ({ found: binary !== 'codex', status: binary !== 'codex' ? 'ok' as const : 'missing' as const, path: binary }));
fireEvent.click(enter);
await refusal(en.onboarding.connection.modelUnavailable);
});
@@ -307,7 +307,7 @@ describe('the correlated entry gate', () => {
mock.api.detectCli.mockClear();
fireEvent.click(enter);
await screen.findByTestId('destination');
- expect(mock.api.detectCli).toHaveBeenCalledWith('/opt/custom/claude-bin');
+ expect(mock.api.detectCli).toHaveBeenCalledWith('/opt/custom/claude-bin', 'claude');
expect(mock.api.detectCli.mock.invocationCallOrder[0]).toBeLessThan(mock.api.mutateConfig.mock.invocationCallOrder[0]);
});
@@ -322,6 +322,7 @@ describe('the correlated entry gate', () => {
const enter = await setup();
mock.api.detectCli.mockImplementation(async (binary: string) => ({
found: binary !== '/opt/custom/claude-bin',
+ status: binary !== '/opt/custom/claude-bin' ? 'ok' as const : 'missing' as const,
path: binary,
}));
fireEvent.click(enter);
diff --git a/ui/src/components/onboarding/entryGate.test.ts b/ui/src/components/onboarding/entryGate.test.ts
index 9ee183787..a983ebb34 100644
--- a/ui/src/components/onboarding/entryGate.test.ts
+++ b/ui/src/components/onboarding/entryGate.test.ts
@@ -48,7 +48,7 @@ const evidence = (overrides: Partial<EntryEvidence> = {}): EntryEvidence => ({
suppliesRead: true,
supplies: [claudeSupply()],
runtime: RUNTIME_OK,
- cliFound: { claude: true, codex: false, opencode: false },
+ cliHealthy: { claude: true, codex: false, opencode: false },
...overrides,
});
@@ -60,10 +60,21 @@ const deps = (overrides: Partial<EntryGateDeps> = {}): EntryGateDeps => ({
getBackendConnection: vi.fn(async (backend) => connection(backend, { application: 'applied', ready: true, entry_eligible: true })),
listAgents: vi.fn(async () => ({ ok: true, agents: [CLAUDE], default_agent_name: null })),
getVibeAgent: vi.fn(async () => ({ ok: false, agent: null as never, default_agent_name: null })),
- detectCli: vi.fn(async (binary: string) => ({ found: true, path: binary })),
+ detectCli: vi.fn(async (binary: string) => ({ found: true, status: 'ok' as const, path: binary })),
...overrides,
});
+describe('CLI health admission', () => {
+ it('does not admit a present but broken CLI even when other owners report ready', async () => {
+ const gate = deps({ detectCli: vi.fn(async () => ({ found: true, path: '/fixture/claude', status: 'broken' as const })) });
+ const read = await readEntryEvidence(gate, { config: { agents: { claude: { cli_path: '/fixture/claude' } } } });
+ expect(read!.cliHealthy.claude).toBe(false);
+ expect(entryCandidates(read!)).toEqual([]);
+ expect(admitEntry(read!).kind).toBe('refused');
+ expect(gate.detectCli).toHaveBeenCalledWith('/fixture/claude', 'claude');
+ });
+});
+
describe('B2 stopped recovery independent of IPC', () => {
it('retains a confirmed stopped controller recovery when IPC supply is unavailable', async () => {
const gate = deps({
@@ -132,21 +143,21 @@ describe('C4 configured-path CLI evidence', () => {
});
it('detects the configured path from the already-fresh prerequisite', async () => {
- const detectCli = vi.fn(async (binary: string) => ({ found: binary === '/opt/custom/claude', path: binary }));
+ const detectCli = vi.fn(async (binary: string) => ({ found: binary === '/opt/custom/claude', status: binary === '/opt/custom/claude' ? 'ok' as const : 'missing' as const, path: binary }));
const gate = deps({ detectCli });
const read = await readEntryEvidence(gate, {
config: { agents: { claude: { enabled: true, cli_path: '/opt/custom/claude' }, codex: { enabled: true } } },
});
- expect(detectCli).toHaveBeenCalledWith('/opt/custom/claude');
- expect(detectCli).toHaveBeenCalledWith('codex');
- expect(detectCli).toHaveBeenCalledWith('opencode');
- expect(read!.cliFound).toEqual({ claude: true, codex: false, opencode: false });
+ expect(detectCli).toHaveBeenCalledWith('/opt/custom/claude', 'claude');
+ expect(detectCli).toHaveBeenCalledWith('codex', 'codex');
+ expect(detectCli).toHaveBeenCalledWith('opencode', 'opencode');
+ expect(read!.cliHealthy).toEqual({ claude: true, codex: false, opencode: false });
});
it('does not admit when detectCli is not found even if installed and cli_present', () => {
const read = evidence({
connections: [connection('claude', { installed: true, ready: true, entry_eligible: true, application: 'applied' })],
- cliFound: { claude: false, codex: false, opencode: false },
+ cliHealthy: { claude: false, codex: false, opencode: false },
});
expect(entryCandidates(read)).toEqual([]);
expect(admitEntry(read)).toMatchObject({ kind: 'refused', startable: false });
@@ -157,14 +168,14 @@ describe('C4 configured-path CLI evidence', () => {
detectCli: vi.fn(async () => { throw new Error('detector unread'); }),
});
const read = await readEntryEvidence(gate);
- expect(read!.cliFound).toEqual({ claude: false, codex: false, opencode: false });
+ expect(read!.cliHealthy).toEqual({ claude: false, codex: false, opencode: false });
expect(admitEntry(read!)).toMatchObject({ kind: 'refused', startable: false });
});
it('does not treat connection.installed as the detector', () => {
const read = evidence({
connections: [connection('claude', { installed: false, ready: true, entry_eligible: true, application: 'applied' })],
- cliFound: { claude: true, codex: false, opencode: false },
+ cliHealthy: { claude: true, codex: false, opencode: false },
});
expect(entryCandidates(read)).toEqual([{ agent: CLAUDE, backend: 'claude', modelId: 'openai/gpt-5.6-sol' }]);
});
@@ -172,7 +183,7 @@ describe('C4 configured-path CLI evidence', () => {
it('cannot release entry on a stale refresh even with a found CLI', async () => {
const gate = deps({
agentReads: { refresh: vi.fn(async () => ({ kind: 'stale' as const })), read: vi.fn(), readValue: vi.fn(), invalidate: vi.fn() },
- detectCli: vi.fn(async () => ({ found: true, path: '/opt/custom/claude' })),
+ detectCli: vi.fn(async () => ({ found: true, status: 'ok' as const, path: '/opt/custom/claude' })),
});
expect(await readEntryEvidence(gate, { config: { agents: { claude: { cli_path: '/opt/custom/claude' } } } })).toBeNull();
});
@@ -190,7 +201,7 @@ describe('D3 a built-in assistant completes setup on its own', () => {
agents: [CLAUDE, VIBEY],
connections: [applied('vibey')],
supplies: [vibeySupply()],
- cliFound: { claude: false, codex: false, opencode: false },
+ cliHealthy: { claude: false, codex: false, opencode: false },
...overrides,
});
@@ -207,7 +218,7 @@ describe('D3 a built-in assistant completes setup on its own', () => {
it('reads the built-in connection with the others and detects only CLIs', async () => {
const getBackendConnection = vi.fn(async (backend: AgentBackendId) => applied(backend));
- const detectCli = vi.fn(async (binary: string) => ({ found: true, path: binary }));
+ const detectCli = vi.fn(async (binary: string) => ({ found: true, status: 'ok' as const, path: binary }));
await readEntryEvidence(deps({ getBackendConnection, detectCli }));
expect(getBackendConnection.mock.calls.map(([backend]) => backend).sort()).toEqual([...SETUP_LINEUP].sort());
expect(detectCli.mock.calls.map(([binary]) => binary)).not.toContain('vibey');
diff --git a/ui/src/components/onboarding/entryGate.ts b/ui/src/components/onboarding/entryGate.ts
index 43ef2b73f..4a6cec25a 100644
--- a/ui/src/components/onboarding/entryGate.ts
+++ b/ui/src/components/onboarding/entryGate.ts
@@ -1,4 +1,4 @@
-import type { BackendConnectionState, VibeAgentBrief, VibeAgentFull } from '../../context/ApiContext';
+import type { BackendConnectionState, VibeAgentBrief, VibeAgentFull, CliStatus } from '../../context/ApiContext';
import type { CollectionReadAuthority } from '../settings/models/collectionReadAuthority';
import { runtimeIsRunning } from '../settings/models/runtimeLifecycle';
import type { AgentSupply, RuntimeDependency, SupplyStatus } from '../settings/models/types';
@@ -50,8 +50,8 @@ export type EntryEvidence = {
supplies: readonly AgentSupply[];
/** Null when the Hub runtime read threw or did not answer. Unread is not "running". */
runtime: RuntimeDependency | null;
- /** Per-backend `detectCli(configured path)` result. Missing keys are not found. */
- cliFound: Readonly<Record<AssistantId, boolean>>;
+ /** Per-backend detection health for that configured path; missing evidence is not healthy. */
+ cliHealthy: Readonly<Record<AssistantId, boolean>>;
};
/**
@@ -108,14 +108,14 @@ const backendUsable = (
backend: AgentBackendId,
connection: BackendConnectionState | undefined,
supply: AgentSupply | undefined,
- cliFound: Readonly<Record<AssistantId, boolean>>,
+ cliHealthy: Readonly<Record<AssistantId, boolean>>,
): boolean =>
connection !== undefined && connection.ok
&& connection.enabled
&& connection.ready && connection.application === 'applied'
&& supply !== undefined
&& (isBuiltinBackend(backend)
- || (supply.cli_present === true && cliFound[backend as AssistantId] === true));
+ || (supply.cli_present === true && cliHealthy[backend as AssistantId] === true));
/**
* Whether the server can route THIS named Agent to a model right now.
@@ -142,7 +142,7 @@ export function entryCandidates(evidence: EntryEvidence): EntryCandidate[] {
const connectionOf = new Map(evidence.connections.map((connection) => [connection.backend, connection]));
const supplyOf = new Map(evidence.supplies.map((supply) => [supply.backend, supply]));
return ENTRY_ORDER.flatMap((backend) => {
- if (!backendUsable(backend, connectionOf.get(backend), supplyOf.get(backend), evidence.cliFound)) return [];
+ if (!backendUsable(backend, connectionOf.get(backend), supplyOf.get(backend), evidence.cliHealthy)) return [];
return evidence.agents
.filter((agent) => agent.backend === backend && usableAgent(agent))
.flatMap((agent) => {
@@ -213,7 +213,7 @@ export type EntryGateDeps = {
name: string,
params?: { cache?: boolean },
) => Promise<{ ok: boolean; agent: VibeAgentFull; default_agent_name: string | null }>;
- detectCli: (binary: string) => Promise<{ found?: boolean; path?: string }>;
+ detectCli: (binary: string, backend: AssistantId) => Promise<{ status: CliStatus }>;
};
export type EntryReadOptions = {
@@ -257,8 +257,8 @@ export async function readEntryEvidence(
asSettled(deps.listAgents()),
Promise.allSettled(ASSISTANT_ORDER.map(async (backend) => {
const path = configuredCliPath(options.config, backend);
- const detected = await deps.detectCli(path);
- return { backend, found: detected?.found === true };
+ const detected = await deps.detectCli(path, backend);
+ return { backend, healthy: detected?.status === 'ok' };
})),
]);
if (supplyOutcome.status === 'fulfilled' && supplyOutcome.value.kind === 'stale') return null;
@@ -270,9 +270,9 @@ export async function readEntryEvidence(
: { ok: false, agents: [] as VibeAgentBrief[], default_agent_name: null };
const listed = agents.ok ? agents.agents : [];
const targets = agents.ok ? await readSetupTargets(listed, deps) : [];
- const cliFound = noneFound();
+ const cliHealthy = noneFound();
for (const result of cliResults) {
- if (result.status === 'fulfilled') cliFound[result.value.backend] = result.value.found;
+ if (result.status === 'fulfilled') cliHealthy[result.value.backend] = result.value.healthy;
}
return {
agentsRead: agents.ok,
@@ -284,6 +284,6 @@ export async function readEntryEvidence(
suppliesRead: supplies !== null,
supplies: supplies ?? [],
runtime: runtimeOutcome.status === 'fulfilled' ? runtimeOutcome.value : null,
- cliFound,
+ cliHealthy,
};
}
diff --git a/ui/src/components/settings/BackendLifecycleChip.test.tsx b/ui/src/components/settings/BackendLifecycleChip.test.tsx
index 8c5954126..8651c09b3 100644
--- a/ui/src/components/settings/BackendLifecycleChip.test.tsx
+++ b/ui/src/components/settings/BackendLifecycleChip.test.tsx
@@ -1,7 +1,7 @@
/* @vitest-environment jsdom */
import { useState } from 'react';
-import { cleanup, render, screen, waitFor, within } from '@testing-library/react';
+import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -38,6 +38,7 @@ const updateAvailable = {
cli_path: codexPath,
resolved_path: codexPath,
installed: true,
+ status: 'ok' as const,
current_version: '1.0.0',
latest_version: '1.1.0',
has_update: true,
@@ -83,6 +84,62 @@ afterEach(() => {
});
describe('BackendLifecycleChip', () => {
+ it('shares the host observation and offers repair for present-but-broken CLI', async () => {
+ const broken = { ...updateAvailable, status: 'broken' as const, current_version: null, has_update: false };
+ api.getBackendRuntime.mockResolvedValue(broken);
+ api.installAgent.mockResolvedValue({ ok: false, message: 'Repair did not verify', code: 'cli_readback_failed' });
+ const changed = vi.fn(); const user = userEvent.setup();
+ render(<BackendLifecycleChip name="codex" enabled cliStatus="broken" cliPath={codexPath} detectedRuntime={broken} onChanged={changed} />);
+ const chip = await screen.findByRole('button', { name: 'backendLifecycle.statusBroken' });
+ expect(api.getBackendRuntime).not.toHaveBeenCalled();
+ await user.click(chip);
+ await waitFor(() => expect(api.getBackendRuntime).toHaveBeenCalledWith('codex', codexPath));
+ await user.click(screen.getByRole('button', { name: 'backendLifecycle.reinstall' }));
+ await waitFor(() => expect(showToast).toHaveBeenCalledWith('Repair did not verify', 'error'));
+ expect(showToast).not.toHaveBeenCalledWith('backendLifecycle.upgradeSuccess', 'success');
+ expect(screen.queryByText('backendLifecycle.readyHint')).toBeNull();
+ });
+
+ it('probes the draft path but cannot mutate the saved installation until the draft is saved', async () => {
+ const draft = '/draft/不同的 codex';
+ const info = { ...updateAvailable, cli_path: draft, resolved_path: draft, current_version: '2.0.0' };
+ api.getBackendRuntime.mockResolvedValue(info);
+ const user = userEvent.setup();
+ render(<BackendLifecycleChip name="codex" enabled cliStatus="ok" cliPath={draft} selectionUnsaved />);
+ await user.click(await screen.findByRole('button', { name: 'backendLifecycle.statusUpdateAvailable' }));
+ expect(api.getBackendRuntime).toHaveBeenCalledWith('codex', draft);
+ expect(screen.getByText('2.0.0')).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'backendLifecycle.upgradeNow' }).hasAttribute('disabled')).toBe(true);
+ expect(screen.getByText('backendLifecycle.savePathFirst')).toBeTruthy();
+ expect(api.installAgent).not.toHaveBeenCalled();
+ });
+
+ it('does not retain a green verdict after the latest runtime observation fails', async () => {
+ const healthy = { ...updateAvailable, has_update: false };
+ const changed = vi.fn(); const user = userEvent.setup();
+ api.getBackendRuntime.mockRejectedValue(new Error('fixture offline'));
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});
+ render(<BackendLifecycleChip name="codex" enabled cliStatus="ok" cliPath={codexPath} detectedRuntime={healthy} onChanged={changed} />);
+ await user.click(await screen.findByRole('button', { name: 'backendLifecycle.statusReady' }));
+ await waitFor(() => expect(changed).toHaveBeenCalledWith({ observation: expect.objectContaining({ cli_path: codexPath, status: 'unknown' }) }));
+ expect(screen.queryByRole('button', { name: 'backendLifecycle.statusReady' })).toBeNull();
+ log.mockRestore();
+ });
+
+ it('discards an old-path completion after a newer selected path was observed', async () => {
+ const old = deferred<typeof updateAvailable>(); const nextPath = '/new/codex';
+ const next = { ...updateAvailable, cli_path: nextPath, resolved_path: nextPath, has_update: false, current_version: '2.0.0' };
+ api.getBackendRuntime.mockImplementation((_name, path) => path === codexPath ? old.promise : Promise.resolve(next));
+ const user = userEvent.setup();
+ const view = render(<BackendLifecycleChip name="codex" enabled cliStatus="ok" cliPath={codexPath} />);
+ view.rerender(<BackendLifecycleChip name="codex" enabled cliStatus="ok" cliPath={nextPath} />);
+ await screen.findByRole('button', { name: 'backendLifecycle.statusReady' });
+ await act(async () => old.resolve(updateAvailable));
+ await user.click(screen.getByRole('button', { name: 'backendLifecycle.statusReady' }));
+ expect(await screen.findByText('2.0.0')).toBeTruthy();
+ expect(screen.queryByText('1.0.0')).toBeNull();
+ });
+
it('saves the backend auto-update switch to its own agent config', async () => {
api.getBackendRuntime.mockResolvedValue({ ...updateAvailable, auto_update: true });
api.mutateConfig.mockResolvedValue({ ok: true });
diff --git a/ui/src/components/settings/BackendLifecycleChip.tsx b/ui/src/components/settings/BackendLifecycleChip.tsx
index feac7c21f..8584254df 100644
--- a/ui/src/components/settings/BackendLifecycleChip.tsx
+++ b/ui/src/components/settings/BackendLifecycleChip.tsx
@@ -2,7 +2,7 @@ import React from 'react';
import { useTranslation } from 'react-i18next';
import { AlertCircle, Check, Download, RefreshCw, RotateCw, X } from 'lucide-react';
import clsx from 'clsx';
-import { useApi, type BackendRuntimeInfo } from '../../context/ApiContext';
+import { useApi, type BackendRuntimeInfo, type CliStatus } from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
import { InstallOutcome, type InstallOutcomeResult } from '../shared/InstallOutcome';
import { Button } from '../ui/button';
@@ -16,7 +16,6 @@ import { getBackendUiMeta } from '@/lib/agentBackends';
import { setConfigField } from '@/lib/configMutations';
import { cn } from '@/lib/utils';
-type CliStatus = 'unknown' | 'ok' | 'missing';
type Operation = 'idle' | 'upgrading' | 'restarting';
type Visual = 'disabled' | 'ready' | 'updating' | 'update' | 'error' | 'loading';
@@ -30,6 +29,8 @@ export type BackendChipChange = {
// path from the React closure keeps the row in a false ``missing`` state
// even though the install succeeded.
installedPath?: string | null;
+ /** Fresh owner observation from a manual lifecycle refresh; not a config write. */
+ observation?: BackendRuntimeInfo;
};
interface BackendLifecycleChipProps {
@@ -40,6 +41,9 @@ interface BackendLifecycleChipProps {
the executable it ran against, so its explanation retires once the host
detects a different one. */
cliPath: string;
+ detectedRuntime?: BackendRuntimeInfo;
+ /** Installation/restart acts on persisted config, never an unsaved draft. */
+ selectionUnsaved?: boolean;
/** Setup describes executable availability separately from connection readiness. */
readyLabel?: string;
/** Setup reads an off switch as a step the person has not taken yet, not as a
@@ -96,13 +100,9 @@ const deriveVisual = (
// backend off mid-install we still want the progress affordance visible.
if (operation === 'upgrading') return 'updating';
if (!enabled) return 'disabled';
- if (cliStatus === 'missing') return 'error';
- // ``runtime.installed`` is probed against the *persisted* cli_path. When
- // the user edits the row's path and runs Detect, ``cliStatus`` flips to
- // ``ok`` but the runtime probe is still inspecting the saved config. In
- // that window the local detection is the fresher signal — trust it and
- // do not flip the chip to error just because the saved config is stale.
- if (cliStatus !== 'ok' && runtime && runtime.installed === false) return 'error';
+ if (cliStatus === 'missing' || cliStatus === 'broken') return 'error';
+ if (cliStatus === 'ok' && runtime?.status === 'broken') return 'error';
+ if (cliStatus === 'ok' && runtime?.status === 'missing') return 'error';
// A change the host applied is not done until the probe it asked for has read
// it back, just as the chip's own upgrade stays in progress through its probe;
// until then the runtime still describes the CLI from before the change.
@@ -111,17 +111,11 @@ const deriveVisual = (
// stay stopped until a session needs them, so ``process_status === 'stopped'``
// is the normal idle state, not an error. Restart still works on demand
// from the popover.
+ if (cliStatus !== 'ok' || runtime?.status === 'unknown') return 'loading';
if (runtime?.has_update) return 'update';
- // After a successful upgrade, ``cliStatus`` can briefly hang at ``unknown``
- // — the chip's own ``loadRuntime`` already returned a fresh runtime
- // (``installed=true``) but the parent's separate ``detect()`` call (which
- // owns the prop) is still in flight. Without the second clause here,
- // ``deriveVisual`` falls through to ``loading`` and the user sees
- // "未检测" until the parent's detect resolves and triggers a re-render.
- // Treating ``runtime.installed=true`` as a ready signal closes that
- // race — the runtime probe is the authoritative source on whether the
- // binary is on disk and produces a version string.
- if (cliStatus === 'ok' || runtime?.installed === true) return 'ready';
+ // Presence is not health. An in-flight/failed detection cannot be made
+ // ready by an older saved-path lifecycle response.
+ if (cliStatus === 'ok') return 'ready';
return 'loading';
};
@@ -130,6 +124,8 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
enabled,
cliStatus,
cliPath,
+ detectedRuntime,
+ selectionUnsaved = false,
onChanged,
onOperationChange,
readyLabel,
@@ -142,7 +138,10 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
const api = useApi();
const { showToast } = useToast();
const [isOpen, setIsOpen] = React.useState(false);
- const [runtime, setRuntime] = React.useState<BackendRuntimeInfo | null>(null);
+ const [runtime, setRuntime] = React.useState<BackendRuntimeInfo | null>(detectedRuntime ?? null);
+ const onChangedRef = React.useRef(onChanged);
+ onChangedRef.current = onChanged;
+ const previousEnabled = React.useRef(enabled);
const [runtimeLoading, setRuntimeLoading] = React.useState(false);
const [operation, setOperation] = React.useState<Operation>('idle');
const [savingAutoUpdate, setSavingAutoUpdate] = React.useState(false);
@@ -184,39 +183,48 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
return () => document.removeEventListener('mousedown', handleClickOutside);
}, [isOpen]);
- const loadRuntime = React.useCallback(async () => {
+ const loadRuntime = React.useCallback(async (notifyHost = true) => {
const myToken = ++loadTokenRef.current;
const key = refreshKeyRef.current;
setRuntimeLoading(true);
let info: BackendRuntimeInfo | null = null;
try {
- info = await api.getBackendRuntime(name);
+ info = await api.getBackendRuntime(name, cliPath || name);
} catch (e) {
console.error(`Failed to load runtime for ${name}:`, e);
+ info = { ok: false, cli_path: cliPath || name, status: 'unknown' };
} finally {
// Drop the result if a newer request superseded us, or the component
// unmounted while we were in flight.
- if (isMountedRef.current && loadTokenRef.current === myToken) {
+ if (isMountedRef.current && loadTokenRef.current === myToken && refreshKeyRef.current === key) {
setRuntime(info);
setProbedKey(key);
setRuntimeLoading(false);
+ if (notifyHost && info) await onChangedRef.current?.({ observation: info });
}
}
- }, [api, name]);
+ }, [api, name, cliPath]);
// Refresh when the user toggles enabled or when the CLI path is freshly
// detected. Runtime loading is independent from a long-running operation so
// a probe can never replace an active upgrade with stale version data.
React.useEffect(() => {
- if (!enabled) {
- // Bump the token so any in-flight probe drops its result.
- loadTokenRef.current += 1;
+ const reenabled = enabled && !previousEnabled.current;
+ previousEnabled.current = enabled;
+ loadTokenRef.current += 1;
+ if (!enabled || cliStatus === 'unknown') {
setRuntime(null);
setRuntimeLoading(false);
return;
}
- if (cliStatus === 'ok') void loadRuntime();
- }, [enabled, cliStatus, loadRuntime, refreshKey]);
+ if (detectedRuntime && !reenabled) {
+ setRuntime(detectedRuntime);
+ setProbedKey(refreshKey);
+ setRuntimeLoading(false);
+ } else {
+ void loadRuntime();
+ }
+ }, [enabled, cliStatus, cliPath, detectedRuntime, loadRuntime, refreshKey]);
// Opening asks for a fresh projection; closing is presentation-only and
// must not mutate lifecycle state.
@@ -226,7 +234,12 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
// The effect above probes whenever the host refreshes an enabled, detected CLI.
const confirming = enabled && cliStatus === 'ok' && probedKey !== refreshKey;
- const visual = deriveVisual(enabled, cliStatus, runtime, operation, confirming);
+ const boundRuntime = runtime && (runtime.cli_path === (cliPath || name) || runtime.resolved_path === cliPath) ? runtime : null;
+ const visual = deriveVisual(enabled, runtimeLoading ? 'unknown' : cliStatus, boundRuntime,
+ externallyBusy && operation === 'idle' ? 'upgrading' : operation, confirming);
+ const reportedStatus: CliStatus = cliStatus === 'broken' || boundRuntime?.status === 'broken' ? 'broken' : cliStatus;
+ const presentationRuntime: BackendRuntimeInfo = { ...boundRuntime, ok: boundRuntime?.ok ?? false, status: reportedStatus,
+ current_version: reportedStatus === 'ok' ? boundRuntime?.current_version : null };
const busy = runtimeLoading || operation !== 'idle' || externallyBusy;
const shownFailure =
failure && failure.cliPath === cliPath && failure.refreshKey === refreshKey && visual !== 'disabled'
@@ -238,6 +251,7 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
}, [visual, onVisual]);
const handleUpgrade = async () => {
+ if (selectionUnsaved) return;
setOperation('upgrading');
setFailure(null);
onOperationChange?.(true);
@@ -262,8 +276,8 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
// Failed or not, the attempt may have replaced or removed the CLI.
// The probe reads what it left, and the host re-detects the file its
// status describes, or a CLI the attempt removed goes on reading as ready.
- await loadRuntime();
- await onChanged?.({ installedPath });
+ if (onChanged) await onChanged({ installedPath });
+ else await loadRuntime(false);
} finally {
onOperationChange?.(false);
if (isMountedRef.current) setOperation('idle');
@@ -283,6 +297,7 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
};
const handleRestart = async () => {
+ if (selectionUnsaved) return;
setOperation('restarting');
onOperationChange?.(true);
try {
@@ -311,7 +326,7 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
case 'update':
return t('backendLifecycle.statusUpdateAvailable');
case 'error':
- return t('backendLifecycle.statusError');
+ return t(cliStatus === 'broken' || boundRuntime?.status === 'broken' ? 'backendLifecycle.statusBroken' : 'backendLifecycle.statusError');
case 'loading':
default:
return t('common.notChecked');
@@ -371,12 +386,13 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
<div className="space-y-3 p-4">
<ChipPopoverBody
visual={visual}
- runtime={runtime}
+ runtime={presentationRuntime}
operation={operation}
name={name}
failed={!!shownFailure}
/>
{shownFailure && <InstallOutcome result={shownFailure} className="text-xs" />}
+ {selectionUnsaved && <p className="text-xs text-muted">{t('backendLifecycle.savePathFirst')}</p>}
{visual !== 'disabled' && typeof runtime?.auto_update === 'boolean' && (
<div className="flex items-center justify-between gap-3 border-t border-border pt-3">
<div className="min-w-0">
@@ -386,7 +402,7 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
<ToggleSwitch
enabled={runtime.auto_update}
onClick={() => void handleAutoUpdateToggle(!runtime.auto_update)}
- disabled={savingAutoUpdate}
+ disabled={savingAutoUpdate || selectionUnsaved}
label={t('backendLifecycle.autoUpdate')}
/>
</div>
@@ -396,13 +412,13 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
{visual !== 'disabled' && visual !== 'updating' && (
<div className="flex flex-wrap justify-end gap-2 border-t border-border px-4 py-3">
{visual === 'update' && (
- <Button variant="brand" size="xs" onClick={() => void handleUpgrade()} disabled={busy}>
+ <Button variant="brand" size="xs" onClick={() => void handleUpgrade()} disabled={busy || selectionUnsaved}>
<Download size={14} />
{t('backendLifecycle.upgradeNow')}
</Button>
)}
{visual === 'error' && (
- <Button variant="brand" size="xs" onClick={() => void handleUpgrade()} disabled={busy}>
+ <Button variant="brand" size="xs" onClick={() => void handleUpgrade()} disabled={busy || selectionUnsaved}>
<Download size={14} />
{t('backendLifecycle.reinstall')}
</Button>
@@ -412,7 +428,7 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
variant="secondary"
size="xs"
onClick={() => void handleRestart()}
- disabled={busy}
+ disabled={busy || selectionUnsaved}
>
<RotateCw size={14} className={operation === 'restarting' ? 'animate-spin' : ''} />
{t('backendLifecycle.restart')}
@@ -489,7 +505,7 @@ const StateBlock: React.FC<{
return (
<div className="flex items-center gap-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive-ink">
<AlertCircle size={16} className="shrink-0" />
- <span>{t('backendLifecycle.errorHint', { name: label })}</span>
+ <span>{t(runtime?.status === 'broken' ? 'backendLifecycle.brokenHint' : 'backendLifecycle.errorHint', { name: label })}</span>
</div>
);
}
diff --git a/ui/src/components/settings/SettingsBackendsPage.test.tsx b/ui/src/components/settings/SettingsBackendsPage.test.tsx
index 0c98078db..ed8e87e77 100644
--- a/ui/src/components/settings/SettingsBackendsPage.test.tsx
+++ b/ui/src/components/settings/SettingsBackendsPage.test.tsx
@@ -37,7 +37,7 @@ beforeEach(async () => {
vi.clearAllMocks();
await i18n.changeLanguage('en');
mocks.api.getConfig.mockResolvedValue({ agents: {} });
- mocks.api.detectCli.mockImplementation(async (binary: string) => ({ found: true, path: binary }));
+ mocks.api.detectCli.mockImplementation(async (binary: string) => ({ found: true, status: 'ok' as const, path: binary }));
});
afterEach(() => {
diff --git a/ui/src/components/settings/SettingsBackendsPage.tsx b/ui/src/components/settings/SettingsBackendsPage.tsx
index 581c6cbb2..0aa95eef6 100644
--- a/ui/src/components/settings/SettingsBackendsPage.tsx
+++ b/ui/src/components/settings/SettingsBackendsPage.tsx
@@ -11,7 +11,7 @@ import { SettingsPageShell } from './SettingsPageShell';
import { hubSupplyBlocks, type HubSupplyBlock } from './models/featureFlags';
import { modelsApi } from './models/modelsApi';
import { agentsWithoutModel } from './models/supply';
-import { useApi } from '@/context/ApiContext';
+import { useApi, type CliStatus, type BackendRuntimeInfo } from '@/context/ApiContext';
import { useToast } from '@/context/ToastContext';
import { AGENT_BACKENDS, DEFAULT_AGENT_STATE, getBackendUiMeta } from '@/lib/agentBackends';
import { configChanges } from '@/lib/configMutations';
@@ -25,12 +25,11 @@ import { errorMessage } from '@/lib/errorMessage';
// detect, install, and permission profile live on the provider page now —
// keep the level-1 page about backend availability, not Agent defaults.
-type CliStatus = 'unknown' | 'ok' | 'missing';
-
type AgentState = {
enabled: boolean;
cli_path?: string;
status: CliStatus;
+ detectedRuntime?: BackendRuntimeInfo;
};
const DEFAULT_AGENTS = DEFAULT_AGENT_STATE as Record<string, AgentState>;
@@ -102,7 +101,7 @@ export const SettingsBackendsPage: React.FC = () => {
const results = await Promise.all(
Object.entries(agents).filter(([name]) => getBackendUiMeta(name).capabilities.supports_cli).map(async ([name, agent]) => {
try {
- const result = await api.detectCli(agent.cli_path || name);
+ const result = await api.detectCli(agent.cli_path || name, name);
return [name, result] as const;
} catch {
return [name, null] as const;
@@ -117,7 +116,8 @@ export const SettingsBackendsPage: React.FC = () => {
next[name] = {
...next[name],
cli_path: result.path || next[name].cli_path,
- status: result.found ? 'ok' : 'missing',
+ status: result.status,
+ detectedRuntime: result.runtime,
};
}
return next;
@@ -151,13 +151,14 @@ export const SettingsBackendsPage: React.FC = () => {
const refreshDetectionFor = async (name: string, cli_path?: string) => {
try {
- const result = await api.detectCli(cli_path || name);
+ const result = await api.detectCli(cli_path || name, name);
setAgents((prev) => ({
...prev,
[name]: {
...prev[name],
cli_path: result.path || prev[name].cli_path,
- status: result.found ? 'ok' : 'missing',
+ status: result.status,
+ detectedRuntime: result.runtime,
},
}));
} catch {
@@ -207,7 +208,15 @@ export const SettingsBackendsPage: React.FC = () => {
enabled={agent.enabled}
cliStatus={agent.status}
cliPath={agent.cli_path || ''}
+ detectedRuntime={agent.detectedRuntime}
onChanged={async (info) => {
+ const observed = info?.observation;
+ if (observed) {
+ setAgents((prev) => observed.cli_path === (prev[meta.id].cli_path || meta.id)
+ ? { ...prev, [meta.id]: { ...prev[meta.id], cli_path: observed.resolved_path || prev[meta.id].cli_path,
+ status: observed.status || 'unknown', detectedRuntime: observed } } : prev);
+ return;
+ }
const installedPath = info?.installedPath || null;
if (installedPath) {
setAgents((prev) => ({
diff --git a/ui/src/components/settings/shared/BackendRuntimeCard.tsx b/ui/src/components/settings/shared/BackendRuntimeCard.tsx
index 1fb9f321a..bca6ae677 100644
--- a/ui/src/components/settings/shared/BackendRuntimeCard.tsx
+++ b/ui/src/components/settings/shared/BackendRuntimeCard.tsx
@@ -108,6 +108,8 @@ export const BackendRuntimeCard: React.FC<BackendRuntimeCardProps> = ({
enabled={runtime.enabled}
cliStatus={runtime.cliStatus}
cliPath={runtime.cliPath}
+ detectedRuntime={runtime.detectedRuntime}
+ selectionUnsaved={runtime.runtimeDirty}
onChanged={runtime.handleLifecycleChanged}
onOperationChange={(busy) => { if (!busy) void runtime.handleLifecycleChanged(null); }}
/>}
@@ -152,14 +154,14 @@ export const BackendRuntimeCard: React.FC<BackendRuntimeCardProps> = ({
<p className="text-[12px] text-muted">{t('settings.backends.cliPathHint')}</p>
</div>}
- {capabilities.supports_install && runtime.cliStatus === 'missing' && (
+ {capabilities.supports_install && (runtime.cliStatus === 'missing' || runtime.cliStatus === 'broken') && (
<div className="space-y-2 rounded-lg border border-cyan/30 bg-cyan/[0.06] px-3 py-2.5">
- <p className="text-[12px] text-cyan-ink">{t('agentDetection.installHint')}</p>
+ <p className="text-[12px] text-cyan-ink">{t(runtime.cliStatus === 'broken' ? 'backendLifecycle.brokenHint' : 'agentDetection.installHint', { name: label })}</p>
<Button
variant="brand-cyan"
size="xs"
onClick={() => void runtime.install()}
- disabled={runtime.installing}
+ disabled={runtime.installing || runtime.runtimeDirty}
>
{runtime.installing ? (
<RefreshCw className="size-3.5 animate-spin" />
@@ -168,8 +170,9 @@ export const BackendRuntimeCard: React.FC<BackendRuntimeCardProps> = ({
)}
{runtime.installing
? t('agentDetection.installing')
- : t('agentDetection.installAgent')}
+ : t(runtime.cliStatus === 'broken' ? 'backendLifecycle.reinstall' : 'agentDetection.installAgent')}
</Button>
+ {runtime.runtimeDirty && <p className="text-xs text-muted">{t('backendLifecycle.savePathFirst')}</p>}
{runtime.installResult && (
<InstallOutcome result={runtime.installResult} className="text-[12px]" />
)}
diff --git a/ui/src/components/settings/shared/useBackendRuntime.test.tsx b/ui/src/components/settings/shared/useBackendRuntime.test.tsx
index 5ddfaa763..6d9f25d43 100644
--- a/ui/src/components/settings/shared/useBackendRuntime.test.tsx
+++ b/ui/src/components/settings/shared/useBackendRuntime.test.tsx
@@ -30,7 +30,7 @@ beforeEach(() => {
agents: { claude: { enabled: true, cli_path: 'claude' } },
});
mocks.api.detectCli.mockImplementation(async (binary: string) => ({
- found: true,
+ found: true, status: 'ok' as const,
path: binary,
}));
mocks.api.installAgent.mockResolvedValue({
@@ -41,6 +41,12 @@ beforeEach(() => {
mocks.api.saveConfig.mockResolvedValue({});
});
+const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => { resolve = done; });
+ return { promise, resolve };
+};
+
const mountRuntime = async () => {
const hook = renderHook(() =>
useBackendRuntime({ backend: 'claude', defaultCli: 'claude' }),
@@ -51,6 +57,56 @@ const mountRuntime = async () => {
};
describe('persisted backend install paths', () => {
+ it('retains a missing saved path on initial observation and explicit retry', async () => {
+ const path = '/saved/不存在/claude';
+ mocks.api.getConfig.mockResolvedValue({ agents: { claude: { enabled: true, cli_path: path } } });
+ mocks.api.detectCli.mockResolvedValue({ found: false, path: null, status: 'missing' });
+ const hook = await mountRuntime();
+ expect(hook.result.current.cliPath).toBe(path);
+ expect(hook.result.current.runtimeDirty).toBe(false);
+ await act(async () => hook.result.current.detect(path));
+ expect(mocks.api.detectCli).toHaveBeenLastCalledWith(path, 'claude');
+ expect(hook.result.current.cliPath).toBe(path);
+ });
+
+ it('does not overwrite a newer human edit with a missing initial-path completion', async () => {
+ const path = '/saved/claude';
+ const pending = deferred<{ found: boolean; path: null; status: 'missing' }>();
+ mocks.api.getConfig.mockResolvedValue({ agents: { claude: { enabled: true, cli_path: path } } });
+ mocks.api.detectCli.mockReturnValue(pending.promise);
+ const hook = renderHook(() => useBackendRuntime({ backend: 'claude', showToast: mocks.showToast }));
+ await waitFor(() => expect(hook.result.current.loaded).toBe(true));
+ act(() => hook.result.current.setCliPath('/new-human/claude'));
+ await act(async () => pending.resolve({ found: false, path: null, status: 'missing' }));
+ expect(hook.result.current.cliPath).toBe('/new-human/claude');
+ expect(hook.result.current.runtimeDirty).toBe(true);
+ // The saved path is private hook state; returning to it clears the draft.
+ act(() => hook.result.current.setCliPath(path));
+ expect(hook.result.current.runtimeDirty).toBe(false);
+ });
+
+ it('reports a present but broken CLI without converting presence to health', async () => {
+ mocks.api.detectCli.mockResolvedValue({ found: true, path: '/broken/claude', status: 'broken' });
+ const hook = await mountRuntime();
+ expect(hook.result.current.cliStatus).toBe('broken');
+ expect(mocks.api.detectCli).toHaveBeenCalledWith('claude', 'claude');
+ });
+
+ it('does not install the saved CLI while the person is inspecting another unsaved path', async () => {
+ const hook = await mountRuntime();
+ act(() => hook.result.current.setCliPath('/draft/claude'));
+ await act(async () => hook.result.current.install());
+ expect(mocks.api.installAgent).not.toHaveBeenCalled();
+ expect(hook.result.current.runtimeDirty).toBe(true);
+ });
+
+ it('does not mistake automatic discovery of the saved command for a human draft', async () => {
+ mocks.api.detectCli.mockResolvedValue({ found: true, path: '/resolved/claude', status: 'ok' });
+ const hook = await mountRuntime();
+ expect(hook.result.current.cliPath).toBe('/resolved/claude');
+ expect(hook.result.current.runtimeDirty).toBe(false);
+ });
+
it('reads the built-in backend as enabled without a config section and rejects CLI work at the hook boundary', async () => {
const hook = renderHook(() => useBackendRuntime({ backend: 'vibey' }));
await waitFor(() => expect(hook.result.current.loaded).toBe(true));
diff --git a/ui/src/components/settings/shared/useBackendRuntime.ts b/ui/src/components/settings/shared/useBackendRuntime.ts
index 2043e2b32..f2acbdbc5 100644
--- a/ui/src/components/settings/shared/useBackendRuntime.ts
+++ b/ui/src/components/settings/shared/useBackendRuntime.ts
@@ -1,13 +1,14 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useApi, type InstallResult } from '@/context/ApiContext';
+import { useApi, type InstallResult, type CliStatus, type BackendRuntimeInfo } from '@/context/ApiContext';
import { useToast } from '@/context/ToastContext';
import { setConfigField } from '@/lib/configMutations';
import { errorMessage } from '@/lib/errorMessage';
import { getBackendUiMeta, type AgentBackendId } from '@/lib/agentBackends';
+import type { BackendChipChange } from '../BackendLifecycleChip';
-export type CliStatus = 'unknown' | 'ok' | 'missing';
+export type { CliStatus } from '@/context/ApiContext';
export type BackendId = AgentBackendId;
@@ -33,6 +34,7 @@ export interface BackendRuntimeState {
enabled: boolean;
cliPath: string;
cliStatus: CliStatus;
+ detectedRuntime?: BackendRuntimeInfo;
detecting: boolean;
installing: boolean;
installResult: InstallResult | null;
@@ -57,7 +59,7 @@ export interface BackendRuntimeState {
* notification from onOperationChange(false) observes every settlement,
* including rejected restart/upgrade, without modifying a path draft.
*/
- handleLifecycleChanged: (info: { installedPath?: string | null } | undefined | null) => Promise<void>;
+ handleLifecycleChanged: (info: BackendChipChange | undefined | null) => Promise<void>;
}
type BackendRuntimeApplyResult = {
@@ -115,6 +117,7 @@ export function useBackendRuntime({
const [cliPath, setCliPath] = useState(defaultCli);
const [savedCliPath, setSavedCliPath] = useState(defaultCli);
const [cliStatus, setCliStatus] = useState<CliStatus>('unknown');
+ const [detectedRuntime, setDetectedRuntime] = useState<BackendRuntimeInfo>();
const [detecting, setDetecting] = useState(false);
const [installing, setInstalling] = useState(false);
const [installResult, setInstallResult] = useState<InstallResult | null>(null);
@@ -123,6 +126,7 @@ export function useBackendRuntime({
const mutationQueue = useRef(Promise.resolve());
const enabledIntent = useRef(0);
const pathIntent = useRef(0);
+ const savedPathIntent = useRef(0);
const detectionToken = useRef(0);
const pathState = useRef({ cliPath, savedCliPath });
pathState.current = { cliPath, savedCliPath };
@@ -137,22 +141,26 @@ export function useBackendRuntime({
if (!supportsCli) return;
const token = ++detectionToken.current;
const intent = pathIntent.current;
+ const requestedPath = binary || cliPath || defaultCli;
setDetecting(true);
+ setCliStatus('unknown');
+ setDetectedRuntime(undefined);
try {
- const result = await api.detectCli(binary || cliPath || defaultCli);
+ const result = await api.detectCli(requestedPath, backend);
if (!mounted.current || detectionToken.current !== token || pathIntent.current !== intent) return;
- const nextPath = result.path || cliPath || defaultCli;
+ const nextPath = result.path || requestedPath;
setCliPath(nextPath);
- setCliStatus(result.found ? 'ok' : 'missing');
+ setCliStatus(result.status);
+ setDetectedRuntime(result.runtime);
} catch (e) {
if (!mounted.current || detectionToken.current !== token || pathIntent.current !== intent) return;
- setCliStatus('missing');
+ setCliStatus('unknown');
showToast(errorMessage(e) || t('common.saveFailed'), 'error');
} finally {
if (mounted.current && detectionToken.current === token) setDetecting(false);
}
},
- [api, cliPath, defaultCli, showToast, supportsCli, t],
+ [api, backend, cliPath, defaultCli, showToast, supportsCli, t],
);
// Initial load: read V2Config for ``enabled`` + ``cli_path`` and then
@@ -193,7 +201,8 @@ export function useBackendRuntime({
}, [api, backend, defaultCli, defaultEnabled, supportsCli]);
const install = useCallback(async () => {
- if (!supportsInstall) return;
+ if (!supportsInstall || (pathIntent.current !== savedPathIntent.current
+ && pathState.current.cliPath !== pathState.current.savedCliPath)) return;
const intent = pathIntent.current;
setInstalling(true);
setInstallResult(null);
@@ -204,7 +213,7 @@ export function useBackendRuntime({
typeof result.path === 'string' && result.path ? result.path : null;
setInstallResult(result);
if (result.ok) {
- if (installedPath) setSavedCliPath(installedPath);
+ if (installedPath) { setSavedCliPath(installedPath); savedPathIntent.current = intent; }
if (pathIntent.current === intent) {
if (installedPath) setCliPath(installedPath);
await detect(installedPath || cliPath);
@@ -212,11 +221,13 @@ export function useBackendRuntime({
showToast(result.message || t('agentDetection.installAgent'), 'success');
} else {
showToast(result.message || t('common.saveFailed'), 'error');
+ if (pathIntent.current === intent) await detect(pathState.current.cliPath);
}
} catch (e) {
if (!mounted.current) return;
setInstallResult({ ok: false, message: String(e), output: null });
showToast(errorMessage(e) || String(e), 'error');
+ if (pathIntent.current === intent) await detect(pathState.current.cliPath);
} finally {
if (mounted.current) {
setConnectionRevision((revision) => revision + 1);
@@ -229,6 +240,7 @@ export function useBackendRuntime({
if (!supportsCli) return;
setSavingRuntime(true);
const path = cliPath || defaultCli;
+ const intent = pathIntent.current;
// Save edits only the CLI field. Enablement has its own serialized toggle;
// including it here could overwrite a newer optimistic on/off intent.
const operation = mutationQueue.current.then(async () => {
@@ -236,6 +248,7 @@ export function useBackendRuntime({
const saved = await api.mutateConfig([setConfigField(['agents', backend, 'cli_path'], path)]);
if (!mounted.current) return;
setSavedCliPath(path); // persistence succeeded even if application failed
+ savedPathIntent.current = intent;
assertBackendRuntimeApplied(saved, t('common.saveFailed'), t('settings.configRestartRefused'));
showToast(t('common.saved'), 'success');
} catch (e) {
@@ -285,8 +298,16 @@ export function useBackendRuntime({
}, [api, backend, enabled, showToast, t]);
const handleLifecycleChanged = useCallback(
- async (info: { installedPath?: string | null } | undefined | null) => {
+ async (info: BackendChipChange | undefined | null) => {
if (!mounted.current) return;
+ if (info?.observation) {
+ const observed = info.observation;
+ if (observed.cli_path !== (pathState.current.cliPath || defaultCli)) return;
+ setCliPath(observed.resolved_path || pathState.current.cliPath);
+ setCliStatus(observed.status || 'unknown');
+ setDetectedRuntime(observed);
+ return;
+ }
if (!info) {
if (mounted.current) setConnectionRevision((revision) => revision + 1);
return;
@@ -295,15 +316,15 @@ export function useBackendRuntime({
if (installedPath) setSavedCliPath(installedPath);
// The lifecycle chip may still hold the callback from before a user edit.
// Read the current draft before accepting its installed path.
- if (pathState.current.cliPath === pathState.current.savedCliPath) {
+ if (pathIntent.current === savedPathIntent.current || pathState.current.cliPath === pathState.current.savedCliPath) {
if (installedPath) setCliPath(installedPath);
await detect(installedPath || pathState.current.cliPath);
}
},
- [detect],
+ [detect, defaultCli],
);
- const runtimeDirty = supportsCli && cliPath !== savedCliPath;
+ const runtimeDirty = supportsCli && pathIntent.current !== savedPathIntent.current && cliPath !== savedCliPath;
return {
loaded,
@@ -311,13 +332,14 @@ export function useBackendRuntime({
enabled,
cliPath,
cliStatus,
+ detectedRuntime,
detecting,
installing,
installResult,
savingRuntime,
runtimeDirty,
connectionRevision,
- setCliPath: (next) => { pathIntent.current += 1; setCliPath(next); },
+ setCliPath: (next) => { pathIntent.current += 1; pathState.current = { ...pathState.current, cliPath: next }; setCliPath(next); setCliStatus('unknown'); setDetectedRuntime(undefined); },
detect,
install,
onSaveRuntime,
diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsx
index 1c09ca603..cd0d30515 100644
--- a/ui/src/components/steps/AgentDetection.tsx
+++ b/ui/src/components/steps/AgentDetection.tsx
@@ -23,7 +23,7 @@ import type { BackendId } from '../visual';
import { BackendLifecycleChip, type BackendLifecycleVisual } from '../settings/BackendLifecycleChip';
import { ToggleSwitch } from '../settings/SettingsPrimitives';
import { BackendConnectionDialog } from '../onboarding/BackendConnectionDialog';
-import type { BackendConnectionState } from '@/context/ApiContext';
+import type { BackendConnectionState, BackendRuntimeInfo, CliStatus } from '@/context/ApiContext';
import { setConfigField } from '@/lib/configMutations';
import { OpencodePermissionSetup } from '../settings/shared/OpencodePermissionSetup';
import { hubSupplyBlocks, modelHubEnabledFromConfig } from '../settings/models/featureFlags';
@@ -66,7 +66,8 @@ interface AgentDetectionProps {
type AgentState = {
enabled: boolean;
cli_path: string;
- status?: 'unknown' | 'ok' | 'missing';
+ status?: CliStatus;
+ detectedRuntime?: BackendRuntimeInfo;
};
/** Choosing a built-in assistant's model, a model its list already holds is as much a
@@ -313,7 +314,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
const [chipRefresh, setChipRefresh] = useState<Record<string, number>>({});
const pendingInstalls = useRef(new Set<string>());
const detectionTokens = useRef<Record<string, number>>({});
- const isMissing = (agent: AgentState) => agent.status === 'missing';
+ const needsInstall = (agent: AgentState) => agent.status === 'missing' || agent.status === 'broken';
const refreshConnection = useCallback(async (name: AgentBackendId, { acknowledge = false }: ConnectionRefresh = {}) => {
if (!activeRef.current || pendingEnable.current[name] !== undefined) return;
@@ -409,11 +410,12 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
const token = (detectionTokens.current[name] || 0) + 1;
detectionTokens.current[name] = token;
setDetectingAgents((prev) => ({ ...prev, [name]: true }));
+ setAgents((prev) => ({ ...prev, [name]: { ...prev[name], status: 'unknown', detectedRuntime: undefined } }));
setDetectionErrors((prev) => ({ ...prev, [name]: '' }));
try {
- const result = await api.detectCli(binary || name);
+ const result = await api.detectCli(binary || name, name);
if (epoch !== activation.current || detectionTokens.current[name] !== token) return;
- if (result.found) {
+ if (result.status === 'ok') {
setInstallResults((prev) => {
if (!prev[name] || prev[name].ok) return prev;
const next = { ...prev };
@@ -427,7 +429,8 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
[name]: {
...prev[name],
cli_path: result.path || prev[name].cli_path,
- status: result.found ? 'ok' : 'missing',
+ status: result.status,
+ detectedRuntime: result.runtime,
},
}));
} catch (error) {
@@ -439,6 +442,15 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
}
};
+ const adoptObservation = (name: string, observation: BackendRuntimeInfo) => {
+ if (!activeRef.current) return;
+ setAgents((prev) => {
+ if (observation.cli_path !== (prev[name].cli_path || name)) return prev;
+ return { ...prev, [name]: { ...prev[name], cli_path: observation.resolved_path || prev[name].cli_path,
+ status: observation.status || 'unknown', detectedRuntime: observation } };
+ });
+ };
+
const detectAll = async () => {
await Promise.all(Object.entries(agents).map(([name, agent]) => detect(name, agent.cli_path)));
};
@@ -817,7 +829,9 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
enabled={agent.enabled}
cliStatus={active ? agent.status || 'unknown' : 'unknown'}
cliPath={agent.cli_path}
+ detectedRuntime={active ? agent.detectedRuntime : undefined}
onChanged={async (info) => {
+ if (info?.observation) { adoptObservation(name, info.observation); return; }
// After a successful (re)install the chip hands back the
// path the installer landed at — adopt it before
// detecting, otherwise a stale ``agent.cli_path`` from
@@ -874,7 +888,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
/>
)}
- {isMissing(agent) && (
+ {needsInstall(agent) && (
<>
<Button
type="button"
@@ -890,13 +904,13 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
)}
{installingAgents[name]
? t('agentDetection.installing')
- : t('agentDetection.installAgentNamed', { name: meta.label })}
+ : t(agent.status === 'broken' ? 'backendLifecycle.reinstall' : 'agentDetection.installAgentNamed', { name: meta.label })}
</Button>
</>
)}
</div>
- {isMissing(agent) && installResults[name] && (
+ {needsInstall(agent) && installResults[name] && (
<InstallOutcome result={installResults[name]} className="text-[11px]" />
)}
</div>
@@ -987,7 +1001,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
const hubRoute = mode === 'hub';
return <AssistantRow key={name} backend={name} status={agent.status || 'unknown'}
installing={!!installingAgents[name]} detecting={!!detectingAgents[name]} error={error}
- onInstall={() => void installAgent(name, mode === 'hub')} onDetect={() => void detect(name, agent.cli_path)}
+ onInstall={() => void installAgent(name, mode === 'hub' && agent.status === 'missing')} onDetect={() => void detect(name, agent.cli_path)}
onConfigure={() => {
if (!mode) return;
if (hubRoute) {
@@ -1032,6 +1046,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
onClick={() => toggle(name, !agent.enabled)} />}
lifecycle={<BackendLifecycleChip name={name} enabled={agent.enabled} cliStatus={active ? agent.status || 'unknown' : 'unknown'}
cliPath={agent.cli_path}
+ detectedRuntime={active ? agent.detectedRuntime : undefined}
readyLabel={t('onboarding.setup.enabled')}
disabledLabel={t('onboarding.setup.notEnabled')}
refreshKey={chipRefresh[name]}
@@ -1042,6 +1057,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
if (!pending) void refreshConnection(name);
}}
onChanged={async (info) => {
+ if (info?.observation) { adoptObservation(name, info.observation); return; }
clearInstallResult(name);
const installedPath = info?.installedPath || agent.cli_path;
setAgents((previous) => ({ ...previous, [name]: { ...previous[name], cli_path: installedPath } }));
diff --git a/ui/src/components/steps/Welcome.tsx b/ui/src/components/steps/Welcome.tsx
index 5336a5d08..43cca810f 100644
--- a/ui/src/components/steps/Welcome.tsx
+++ b/ui/src/components/steps/Welcome.tsx
@@ -37,8 +37,8 @@ export function Welcome({ data, onNext, active, ref, onActionChange }: WelcomePr
try {
const results = await Promise.all(ASSISTANT_ORDER.map(async (name) => {
const agent = { ...DEFAULT_NATIVE_AGENT_STATE[name], ...data?.agents?.[name] };
- const result = await api.detectCli(agent.cli_path || name);
- return [name, { ...agent, cli_path: result.path || agent.cli_path, status: result.found ? 'ok' : 'missing' }];
+ const result = await api.detectCli(agent.cli_path || name, name);
+ return [name, { ...agent, cli_path: result.path || agent.cli_path, status: result.status, detectedRuntime: result.runtime }];
}));
await onNext({ agents: Object.fromEntries(results), __onboardingDetected: true });
} catch (cause) {
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index ee245bb6c..78b21acf2 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -606,12 +606,12 @@ export type ApiContextType = {
createBindCode: (type: string, expiresAt?: string) => Promise<any>;
deleteBindCode: (code: string) => Promise<any>;
getFirstBindCode: () => Promise<any>;
- detectCli: (binary: string) => Promise<any>;
+ detectCli: (binary: string, backend?: string) => Promise<CliDetectionResult>;
installAgent: (name: string) => Promise<InstallResult>;
listDependencies: (options?: DependencyReadOptions) => Promise<DependenciesResult>;
installDependency: (dep: string) => Promise<InstallResult>;
getBackendConnection: (name: AgentBackendId) => Promise<BackendConnectionState>;
- getBackendRuntime: (name: string) => Promise<BackendRuntimeInfo>;
+ getBackendRuntime: (name: string, cliPath?: string) => Promise<BackendRuntimeInfo>;
restartBackend: (name: string) => Promise<BackendRestartResult>;
getCodexAuth: () => Promise<CodexAuthState>;
saveCodexAuth: (payload: CodexAuthPayload) => Promise<CodexAuthSaveResult>;
@@ -1987,6 +1987,8 @@ export type BackendConnectionState = {
ok: boolean;
backend: AgentBackendId;
installed: boolean;
+ /** Independent executable evidence; built-in backends do not have a CLI. */
+ cli_status?: CliStatus | null;
enabled: boolean;
// external: launch capability only; the native backend owns authentication.
auth: 'subscription' | 'api_key' | 'external' | 'none' | 'unknown';
@@ -1999,6 +2001,17 @@ export type BackendConnectionState = {
message?: string;
};
+export type CliStatus = 'unknown' | 'ok' | 'missing' | 'broken';
+export type CliDetectionResult = {
+ found: boolean;
+ path: string | null;
+ status: CliStatus;
+ version?: string | null;
+ reason?: string | null;
+ /** The lifecycle projection shares this exact health observation. */
+ runtime?: BackendRuntimeInfo;
+};
+
export type BackendRuntimeInfo = {
ok: boolean;
name?: string;
@@ -2007,6 +2020,8 @@ export type BackendRuntimeInfo = {
cli_path?: string;
resolved_path?: string | null;
installed?: boolean;
+ status?: CliStatus;
+ reason?: string | null;
current_version?: string | null;
latest_version?: string | null;
has_update?: boolean;
@@ -3568,7 +3583,15 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
createBindCode: (type, expiresAt) => postJson('/api/bind-codes', { type, expires_at: expiresAt }),
deleteBindCode: (code) => deleteJson(`/api/bind-codes/${encodeURIComponent(code)}`),
getFirstBindCode: () => getJson('/api/setup/first-bind-code'),
- detectCli: (binary) => getJson(`/api/cli/detect?binary=${encodeURIComponent(binary)}`),
+ detectCli: async (binary, backend) => {
+ if (!backend) return getJson(`/api/cli/detect?binary=${encodeURIComponent(binary)}`);
+ // One owner observation supplies both the host status and its lifecycle
+ // chip; do not immediately launch a second independent version probe.
+ const runtime: BackendRuntimeInfo = await getJson(`/api/backend/${encodeURIComponent(backend)}/runtime?cli_path=${encodeURIComponent(binary)}`);
+ return { found: runtime.installed === true, path: runtime.resolved_path ?? null,
+ status: runtime.status ?? 'unknown', version: runtime.current_version,
+ reason: runtime.reason, runtime };
+ },
installAgent: (name) => startAndPollAgentInstall(name),
listDependencies: ({ ids, signal } = {}) => {
const params = new URLSearchParams();
@@ -3579,7 +3602,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
},
installDependency: (dep) => startAndPollDependencyInstall(dep),
getBackendConnection: (name) => getJson(`/api/backend/${encodeURIComponent(name)}/connection`),
- getBackendRuntime: (name) => getJson(`/api/backend/${encodeURIComponent(name)}/runtime`),
+ getBackendRuntime: (name, cliPath) => getJson(`/api/backend/${encodeURIComponent(name)}/runtime${cliPath === undefined ? '' : `?cli_path=${encodeURIComponent(cliPath)}`}`),
restartBackend: (name) => postJson(`/api/backend/${encodeURIComponent(name)}/restart`, {}),
getCodexAuth: () => getJson('/api/backend/codex/auth'),
saveCodexAuth: (payload) => postJson('/api/backend/codex/auth', payload),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index f50ec9ba9..31ca22d2a 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -3681,6 +3681,9 @@
"statusUpdating": "Updating",
"statusDisabled": "Disabled",
"statusError": "Not installed",
+ "statusBroken": "Can't run",
+ "savePathFirst": "Save the selected CLI path before installing, updating or restarting this backend.",
+ "brokenHint": "{{name}} is installed but cannot run. Check the selected path or reinstall it; retrying alone will not repair the CLI.",
"statusUpdateAvailable": "Update available",
"currentVersion": "Current version",
"latestVersion": "Latest version",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 90c549298..4989d1a32 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -3681,6 +3681,9 @@
"statusUpdating": "升级中",
"statusDisabled": "已停用",
"statusError": "未安装",
+ "statusBroken": "无法运行",
+ "savePathFirst": "请先保存所选 CLI 路径,再安装、更新或重启此后端。",
+ "brokenHint": "{{name}} 已安装但无法运行。请检查所选路径或重新安装;仅重试不会修复 CLI。",
"statusUpdateAvailable": "可升级",
"currentVersion": "当前版本",
"latestVersion": "最新版本",
diff --git a/vibe/api.py b/vibe/api.py
index a9a860049..914b4e35c 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -8,6 +8,7 @@ import os
import platform
import re
import shutil
+import shlex
import socket
import ssl
import stat
@@ -21,7 +22,7 @@ import uuid
from datetime import datetime, timedelta, timezone
from http.client import HTTPSConnection
from pathlib import Path
-from typing import Any, List, Optional
+from typing import Any, Callable, List, Optional
import yaml
from sqlalchemy import select
@@ -70,10 +71,13 @@ from vibe.desktop_backends import (
is_desktop_backend_path,
)
from vibe.desktop_runtime import is_private_desktop_runtime_path
+from vibe.cli_health import CliHealth, probe_cli, probe_cli_sync
+from vibe.cli_repair import REPAIR_PATH_CONFLICT, identify_repair_source, native_bootstrap_env
from vibe.cli_paths import (
_candidate_cli_paths,
_command_env_for,
_is_executable_file,
+ _ordered_cli_candidates,
_npm_binary_candidates_for_prefix,
_npm_global_binary_candidates,
_npm_global_prefixes,
@@ -355,20 +359,42 @@ def resolve_cli_paths(
-def _codex_npm_install_env(npm_path: str, *, prefix: str | Path | None = None) -> dict[str, str]:
+def _codex_npm_install_env(npm_path: str, *, prefix: str | Path | None = None) -> dict[str, str] | None:
env = _command_env_for(npm_path)
+ if prefix is None:
+ if os.name == "nt":
+ # Windows npm's active global prefix is the install command's
+ # destination. Do not let post-install PATH discovery stand in for
+ # an explicit target when this query cannot be completed.
+ prefix = _npm_prefix_for(npm_path)
+ if prefix is None:
+ return None
+ else:
+ prefix = Path.home() / ".local"
+
+ install_prefix = Path(os.path.expanduser(str(prefix)))
+ prefix_text = str(install_prefix)
+ env["NPM_CONFIG_PREFIX"] = prefix_text
if os.name == "nt":
+ path_entries = [entry for entry in env.get("PATH", "").split(os.pathsep) if entry and entry != prefix_text]
+ env["PATH"] = os.pathsep.join([prefix_text, *path_entries])
return env
- install_prefix = Path(os.path.expanduser(str(prefix))) if prefix is not None else Path.home() / ".local"
- prefix = str(install_prefix)
prefix_bin = str(install_prefix / "bin")
path_entries = [entry for entry in env.get("PATH", "").split(os.pathsep) if entry and entry != prefix_bin]
env["PATH"] = os.pathsep.join([prefix_bin, *path_entries])
- env["NPM_CONFIG_PREFIX"] = prefix
return env
+def _declared_codex_npm_target(env: dict[str, str] | None) -> str | None:
+ """The destination the existing npm command policy explicitly declares."""
+ prefix = (env or {}).get("NPM_CONFIG_PREFIX")
+ if not prefix:
+ return None
+ root = Path(prefix).expanduser().absolute()
+ return str(root / ("codex.cmd" if os.name == "nt" else "bin/codex"))
+
+
def _npm_prefix_from_node_modules_path(codex_path: str) -> Path | None:
try:
paths = [Path(codex_path).expanduser(), Path(codex_path).expanduser().resolve()]
@@ -446,49 +472,164 @@ def _is_npm_codex_install(codex_path: str) -> bool:
return False
-def _is_homebrew_codex_install(codex_path: str) -> bool:
- brew_path = resolve_cli_path("brew")
- if not brew_path:
- return False
+def _homebrew_prefix(brew_path: str) -> Path | None:
+ """Return the active Homebrew prefix reported by the selected brew binary."""
+ try:
+ result = subprocess.run(
+ [brew_path, "--prefix"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ env=_command_env_for(brew_path),
+ )
+ except Exception:
+ return None
+ if result.returncode != 0:
+ return None
+ lines = [line.strip() for line in (result.stdout or "").splitlines() if line.strip()]
+ if len(lines) != 1:
+ return None
+ try:
+ prefix = Path(os.path.expanduser(lines[0])).absolute()
+ brew = Path(brew_path).expanduser().absolute()
+ except OSError:
+ return None
+ if brew != prefix / "bin" / "brew":
+ return None
+ return prefix
+
+
+def _homebrew_codex_probe(brew_path: str) -> tuple[str, Path | None, Path | None]:
+ """Inspect the active installed Codex cask without guessing from paths.
+ Returns ``(state, prefix, payload)`` where state is ``installed``,
+ ``not_installed``, or ``unknown``. The JSON ``--installed`` query is
+ supported by Homebrew and distinguishes an absent cask from a failed or
+ malformed metadata query without using the unsupported ``--prefix --cask``
+ command shape.
+ """
+ prefix = _homebrew_prefix(brew_path)
+ if prefix is None:
+ return "unknown", None, None
try:
result = subprocess.run(
- [brew_path, "list", "--cask", "codex"],
+ [brew_path, "info", "--cask", "--json=v2", "--installed", "codex"],
capture_output=True,
text=True,
timeout=10,
env=_command_env_for(brew_path),
)
except Exception:
- return False
+ return "unknown", prefix, None
if result.returncode != 0:
- return False
+ return "unknown", prefix, None
+ try:
+ payload = json.loads(result.stdout or "")
+ if not isinstance(payload, dict):
+ return "unknown", prefix, None
+ casks = payload.get("casks")
+ if not isinstance(casks, list):
+ return "unknown", prefix, None
+ codex_casks = [cask for cask in casks if isinstance(cask, dict) and cask.get("token") == "codex"]
+ if not codex_casks:
+ return "not_installed", prefix, None
+ if len(codex_casks) != 1:
+ return "unknown", prefix, None
+ installed = codex_casks[0].get("installed")
+ if not isinstance(installed, str):
+ return "unknown", prefix, None
+ version = installed
+ version_path = Path(version)
+ if version_path.is_absolute() or len(version_path.parts) != 1 or version_path.name != version:
+ return "unknown", prefix, None
+ except (TypeError, ValueError, json.JSONDecodeError):
+ return "unknown", prefix, None
+ return "installed", prefix, prefix / "Caskroom" / "codex" / version
+
+
+def _homebrew_codex_target(brew_path: str, selected_path: str) -> str | None:
+ """Return a selected Codex launcher attributable to the active cask payload."""
+ selected = Path(selected_path).expanduser()
+ if selected.name not in {"codex", "codex.exe"}:
+ return None
+ state, prefix, payload = _homebrew_codex_probe(brew_path)
+ if state != "installed" or prefix is None or payload is None:
+ return None
+ try:
+ selected_absolute = selected.absolute()
+ expected = (prefix / "bin" / selected.name).absolute()
+ if selected_absolute != expected or not selected.is_symlink():
+ return None
+ resolved = selected.resolve(strict=True)
+ except OSError:
+ return None
+ if not _path_is_relative_to(resolved, payload):
+ return None
+ return str(selected)
+
+def _homebrew_codex_path_is_plausible(
+ codex_path: str,
+ *,
+ brew_path: str | None = None,
+ prefix: Path | None = None,
+) -> bool:
+ """Recognize paths that could belong to a Homebrew Codex cask.
+
+ The selected path must stay attributable before a Homebrew upgrade is
+ allowed, but an unrelated custom executable must not be rejected merely
+ because another Homebrew installation exists. Stable Homebrew locations
+ and resolved ``Caskroom/codex`` payloads are the narrow ownership evidence
+ available without running the selected executable.
+ """
+ selected = Path(codex_path).expanduser()
+ if selected.name not in {"codex", "codex.exe"}:
+ return False
try:
- resolved = Path(codex_path).expanduser().resolve()
+ selected_absolute = selected.absolute()
+ resolved = selected.resolve(strict=False)
except OSError:
return False
- brew_prefixes: list[Path] = []
- for command in ([brew_path, "--prefix"], [brew_path, "--prefix", "--cask"]):
- try:
- prefix_result = subprocess.run(
- command,
- capture_output=True,
- text=True,
- timeout=10,
- env=_command_env_for(brew_path),
- )
- except Exception:
- continue
- if prefix_result.returncode != 0:
- continue
- prefix = (prefix_result.stdout or "").strip().splitlines()
- if prefix:
- brew_prefixes.append(Path(os.path.expanduser(prefix[-1])))
+ prefixes: list[Path] = []
+ if prefix is not None:
+ prefixes.append(prefix.expanduser().absolute())
+ if brew_path:
+ brew_absolute = Path(brew_path).expanduser().absolute()
+ if brew_absolute.name in {"brew", "brew.exe"} and brew_absolute.parent.name == "bin":
+ prefixes.append(brew_absolute.parent.parent)
- brew_prefixes.extend([Path("/opt/homebrew"), Path("/usr/local"), Path("/home/linuxbrew/.linuxbrew")])
- return any(_path_is_relative_to(resolved, prefix) for prefix in brew_prefixes)
+ for candidate in prefixes:
+ for parent in (candidate / "bin", candidate / "Caskroom" / "codex"):
+ try:
+ selected_absolute.relative_to(parent.absolute())
+ return True
+ except (OSError, ValueError):
+ continue
+
+ parts = resolved.parts
+ return any(
+ parts[index : index + 2] == ("Caskroom", "codex")
+ for index in range(len(parts) - 1)
+ )
+
+
+def _is_homebrew_codex_install(codex_path: str) -> bool:
+ brew_path = resolve_cli_path("brew")
+ return bool(brew_path and _homebrew_codex_target(brew_path, codex_path))
+
+
+def _codex_path_is_ambiguous_homebrew_target(
+ codex_path: str,
+ state: str,
+ *,
+ brew_path: str | None = None,
+ prefix: Path | None = None,
+) -> bool:
+ return (
+ state in {"installed", "unknown"}
+ and _homebrew_codex_path_is_plausible(codex_path, brew_path=brew_path, prefix=prefix)
+ )
def _codex_cli_supports_update(codex_path: str) -> bool:
@@ -509,17 +650,27 @@ def _codex_cli_supports_update(codex_path: str) -> bool:
def _codex_upgrade_command(existing_path: str) -> tuple[list[str], dict[str, str] | None] | dict:
- if _is_homebrew_codex_install(existing_path):
- brew_path = resolve_cli_path("brew")
- if not brew_path:
+ brew_path = resolve_cli_path("brew")
+ npm_install = _is_npm_codex_install(existing_path)
+ if brew_path:
+ brew_state, brew_prefix, _ = _homebrew_codex_probe(brew_path)
+ homebrew_target = _homebrew_codex_target(brew_path, existing_path)
+ if homebrew_target is not None:
+ return [brew_path, "upgrade", "--cask", "codex"], None
+ if not npm_install and _codex_path_is_ambiguous_homebrew_target(
+ existing_path,
+ brew_state,
+ brew_path=brew_path,
+ prefix=brew_prefix,
+ ):
return {
"ok": False,
- "message": "Codex appears to be installed via Homebrew, but brew was not found. Please upgrade Codex manually.",
+ "code": "cli_target_unknown",
+ "message": "Codex Homebrew installation target could not be attributed to the selected executable; no upgrade was started.",
"output": None,
}
- return [brew_path, "upgrade", "--cask", "codex"], None
- if _is_npm_codex_install(existing_path):
+ if npm_install:
npm_path = resolve_cli_path("npm")
if not npm_path:
return {
@@ -528,7 +679,15 @@ def _codex_upgrade_command(existing_path: str) -> tuple[list[str], dict[str, str
"output": None,
}
prefix = _npm_prefix_for_existing_codex_install(npm_path, existing_path)
- return [npm_path, "install", "-g", "@openai/codex"], _codex_npm_install_env(npm_path, prefix=prefix)
+ command_env = _codex_npm_install_env(npm_path, prefix=prefix)
+ if command_env is None:
+ return {
+ "ok": False,
+ "code": "cli_target_unknown",
+ "message": "Codex npm global prefix could not be determined; no upgrade was started.",
+ "output": None,
+ }
+ return [npm_path, "install", "-g", "@openai/codex"], command_env
if _codex_cli_supports_update(existing_path):
return [existing_path, "update"], None
@@ -5841,11 +6000,50 @@ def init_sessions() -> None:
store.save()
-def detect_cli(binary: str) -> dict:
+def _cli_detection_target(binary: str, backend: str | None) -> tuple[str | None, str | None]:
+ if backend is None and binary in NATIVE_CLI_BACKENDS:
+ backend = binary
+ if backend is not None and not is_native_cli_backend(backend):
+ raise ValueError("Unknown native CLI backend")
+ # An explicit existing file that lacks execute permission is broken, not
+ # missing. Do not let discovery silently test a different installation.
+ expanded = Path(binary).expanduser() if binary else None
+ explicit = bool(binary) and (os.path.isabs(binary) or os.sep in binary or (os.altsep and os.altsep in binary))
+ if explicit and expanded is not None:
+ if expanded.is_file():
+ return backend, str(expanded.absolute())
+ if backend is not None:
+ return backend, None
path = resolve_cli_path(binary)
- if not path:
- return {"found": False, "path": None}
- return {"found": True, "path": path}
+ if path is None and backend is not None and not explicit:
+ # Discovery normally skips non-executable files. If no runnable candidate
+ # resolved, retain a present candidate so its failed launch is 'broken'.
+ candidates = _ordered_cli_candidates(
+ binary,
+ include_npm_global=True,
+ candidate_paths=_candidate_cli_paths,
+ )
+ path = next((str(p.absolute()) for p in candidates if p.is_file()), None)
+ return backend, path
+
+
+def detect_cli(binary: str, backend: str | None = None) -> dict:
+ """Synchronous CLI/installer entry; HTTP uses detect_cli_async directly."""
+ backend, path = _cli_detection_target(binary, backend)
+ if path is None:
+ return CliHealth(False, None, "missing", reason="not_found").payload()
+ if backend is None:
+ return CliHealth(True, path, "unknown").payload()
+ return probe_cli_sync(backend, path, env=_command_env_for(path)).payload()
+
+
+async def detect_cli_async(binary: str, backend: str | None = None) -> dict:
+ backend, path = await asyncio.to_thread(_cli_detection_target, binary, backend)
+ if path is None:
+ return CliHealth(False, None, "missing", reason="not_found").payload()
+ if backend is None:
+ return CliHealth(True, path, "unknown").payload()
+ return (await probe_cli(backend, path, env=_command_env_for(path))).payload()
def check_cli_exec(path: str) -> dict:
@@ -7602,7 +7800,7 @@ def _agent_install_job_succeeded(result: dict, name: str) -> bool:
return isinstance(restart, dict) and bool(restart.get("ok"))
-def _agent_runtime_fingerprint(name: str) -> tuple[str, str, str] | None:
+def _agent_runtime_fingerprint(name: str, detection: dict | None = None) -> tuple[str, str, str] | None:
"""Measure the configured CLI, not another installation found by name.
Include the persisted launch path as well as its resolved target: changing
@@ -7614,13 +7812,14 @@ def _agent_runtime_fingerprint(name: str) -> tuple[str, str, str] | None:
if config.load_warnings:
return None
configured_path = getattr(config.agents, name).cli_path or name
- resolved_path = resolve_cli_path(configured_path)
- if not resolved_path:
+ if detection is None:
+ detection = detect_cli(configured_path, name)
+ if detection.get("status") != "ok" or not detection.get("version") or not detection.get("path"):
return None
- version = _probe_cli_version(resolved_path)
- if not version:
+ resolved_path = resolve_cli_path(configured_path)
+ if not resolved_path or os.path.abspath(resolved_path) != os.path.abspath(detection["path"]):
return None
- return configured_path, os.path.realpath(resolved_path), version
+ return configured_path, os.path.realpath(resolved_path), detection["version"]
except Exception as exc: # noqa: BLE001
logger.debug("Agent runtime fingerprint probe failed for %s: %s", name, exc)
return None
@@ -7666,9 +7865,14 @@ def start_agent_install_job(name: str) -> dict:
refresh_supported = supports_runtime_refresh(name)
runtime_before = _agent_runtime_fingerprint(name) if refresh_supported else None
result = install_agent(name)
+ verified = result.get("detection")
+ if result.get("ok") and (not isinstance(verified, dict) or verified.get("status") != "ok"
+ or not verified.get("version") or verified.get("path") != result.get("path")):
+ result = {**result, "ok": False, "code": "cli_readback_failed",
+ "message": backend_t("cliHealth.installReadbackFailed", _configured_backend_language())}
if result.get("ok") and refresh_supported:
try:
- runtime_after = _agent_runtime_fingerprint(name)
+ runtime_after = _agent_runtime_fingerprint(name, result.get("detection"))
if runtime_before is None or runtime_before != runtime_after:
result["restart"] = restart_backend(
name,
@@ -7833,7 +8037,13 @@ def _run_desktop_backend_install(name: str, truncate_output) -> dict:
"message": _desktop_backend_install_message(name, exc.code),
"output": truncate_output(exc.output) if exc.output else None,
}
- _invalidate_version_cache(name)
+ health = detect_cli(result.path, name)
+ if health["status"] != "ok":
+ # Publication/activation already committed. Report failed verification,
+ # but never remove the now-active generation as diagnostic cleanup.
+ return {"ok": False, "code": "cli_readback_failed",
+ "message": backend_t("cliHealth.installReadbackFailed", _configured_backend_language()),
+ "path": result.path, "output": None, "detection": health}
return {
"ok": True,
"message": backend_t(
@@ -7842,7 +8052,8 @@ def _run_desktop_backend_install(name: str, truncate_output) -> dict:
backend=_DESKTOP_BACKEND_LABELS.get(name, name),
),
"path": result.path,
- "version": result.version,
+ "version": health["version"],
+ "detection": health,
"managed_by": "desktop",
"output": truncate_output(result.output) if result.output else None,
}
@@ -7873,17 +8084,83 @@ def install_agent(name: str) -> dict:
lock.release()
+def _cli_repair_refusal(name: str, *, conflict: bool = False) -> dict:
+ return {
+ "ok": False,
+ "code": "repair_path_conflict" if conflict else "repair_source_unknown",
+ "message": backend_t("cliHealth.repairPathConflict" if conflict else "cliHealth.repairUnavailable", _configured_backend_language(), backend=display_name_for_backend(name)),
+ "output": None,
+ "path": None,
+ }
+
+
+def _repair_broken_cli(name: str, selected: str, truncate_output) -> dict:
+ source = identify_repair_source(name, selected)
+ if source is None:
+ return _cli_repair_refusal(name)
+ command_env = _command_env_for(selected)
+ if source.kind == "npm":
+ npm = resolve_cli_path("npm")
+ if not npm:
+ return _cli_repair_refusal(name)
+ cmd = [npm, "install", "--global", "--prefix", str(source.prefix), source.package]
+ command_env = _command_env_for(npm)
+ elif source.kind == "brew":
+ brew = source.prefix / "bin" / "brew"
+ if not _is_executable_file(brew):
+ return _cli_repair_refusal(name)
+ cmd = [str(brew), "reinstall", *(["--cask"] if source.cask else []), source.package]
+ command_env = _command_env_for(str(brew))
+ elif name == "opencode":
+ if os.name == "nt":
+ return _cli_repair_refusal(name)
+ bash, curl = resolve_cli_path("bash"), resolve_cli_path("curl")
+ if not bash or not curl:
+ return _cli_repair_refusal(name)
+ command_env = native_bootstrap_env(command_env, hide_directory=Path(source.destination).parent)
+ guard = f"if command -v opencode >/dev/null 2>&1; then printf '%s\\n' {shlex.quote(REPAIR_PATH_CONFLICT)} >&2; exit 73; fi; "
+ # Check before network activity, then in the actual non-login bootstrap
+ # shell. No startup hook/imported function can restore the old PATH.
+ consumer = [bash, "--noprofile", "--norc", "-s", "--", "--no-modify-path"]
+ download = shlex.join([curl, "-fsSL", *shlex.split(_CURL_INSTALL_RETRY_FLAGS), "https://opencode.ai/install"])
+ # Prefix the guard to the streamed script rather than sourcing a pipe
+ # through /dev/stdin (macOS bash may see an empty source before data arrives).
+ script = "set -euo pipefail; " + guard + "{ printf '%s\\n' " + shlex.quote(guard) + "; " + download + "; } | " + shlex.join(consumer)
+ cmd = [bash, "--noprofile", "--norc", "-c", script]
+ elif name == "claude":
+ command_env = native_bootstrap_env(command_env)
+ if os.name == "nt":
+ powershell = resolve_cli_path("powershell")
+ if not powershell:
+ return _cli_repair_refusal(name)
+ cmd = [powershell, "-NoProfile", "-Command", "irm https://claude.ai/install.ps1 -ErrorAction Stop | iex"]
+ else:
+ bash, curl = resolve_cli_path("bash"), resolve_cli_path("curl")
+ if not bash or not curl:
+ return _cli_repair_refusal(name)
+ cmd = [bash, "--noprofile", "--norc", "-c", "set -euo pipefail; " + shlex.join([curl, "-fsSL", *shlex.split(_CURL_INSTALL_RETRY_FLAGS), "https://claude.ai/install.sh"]) + " | " + shlex.join([bash, "--noprofile", "--norc"])]
+ else:
+ return _cli_repair_refusal(name)
+ return _run_install_command(name, cmd, truncate_output, mode="repair", env=command_env, expected_path=source.destination)
+
+
+def _native_vendor_install_target(name: str) -> str | None:
+ home = Path.home()
+ if name == "opencode":
+ return str(home / ".opencode" / "bin" / ("opencode.exe" if os.name == "nt" else "opencode"))
+ if name == "claude":
+ return str(home / ".local" / "bin" / ("claude.exe" if os.name == "nt" else "claude"))
+ return None
+
+
def _install_agent(name: str) -> dict:
"""Install (or upgrade) an agent CLI tool.
- Upgrade path (binary already on disk): keep the user's install method
- stable. Without this, our previous flow bricked Claude installs whenever
- the user's bootstrap method differed from our hard-coded installer URL —
- e.g. the Dockerfile bootstraps via ``npm install -g
- @anthropic-ai/claude-code`` but our upgrade ran ``curl
- https://claude.ai/install.sh | bash``, which migrated the binary to
- ``~/.local/bin/claude`` and left V2Config pointing at the now-empty
- ``/usr/local/bin/claude``.
+ Existing installations keep their install method and their selected
+ executable. Post-upgrade verification is bound before invoking the updater;
+ a missing launcher cannot be replaced by an unrelated same-name discovery.
+ An unattributed relocation fails verification rather than silently changing
+ the configured selection.
Upgrade commands:
- ``claude update`` — auto-detects npm-global vs native install
@@ -7960,7 +8237,25 @@ def _install_agent(name: str) -> dict:
# its place -- the message is about that backend.
"path": private_runtime_path,
}
+ # Preserve the app-private ownership boundary before any global probe or
+ # repair planner can discover a non-executable user installation.
+ if existing_path is None and is_desktop_managed_runtime():
+ return _run_desktop_backend_install(name, _truncate_output)
+ health = detect_cli(configured_path, name)
+ 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)
+ existing_path = health["path"]
if existing_path:
+ readback_validator = None
+ if name == "codex":
+ brew_path = resolve_cli_path("brew")
+ homebrew_target = _homebrew_codex_target(brew_path, existing_path) if brew_path else None
+ if homebrew_target is not None:
+ readback_validator = lambda path, brew=brew_path, expected=homebrew_target: (
+ path == expected and _homebrew_codex_target(brew, path) == expected
+ )
if name == "claude":
cmd = [existing_path, "update"]
command_env = None
@@ -7978,13 +8273,18 @@ def _install_agent(name: str) -> dict:
else:
cmd = None
if cmd is not None:
+ # Codex's existing npm policy may explicitly select a user prefix.
+ # Only that command-declared destination can certify a relocation.
+ declared_target = _declared_codex_npm_target(command_env) if name == "codex" else None
return _run_install_command(
name,
cmd,
_truncate_output,
mode="upgrade",
env=command_env,
- resolve_from=configured_path,
+ expected_path=declared_target or existing_path,
+ preserve_selected_path=existing_path if declared_target else None,
+ readback_validator=readback_validator,
)
# A damaged private toolchain must fail closed. Falling through here would
@@ -7994,6 +8294,7 @@ def _install_agent(name: str) -> dict:
return _run_desktop_backend_install(name, _truncate_output)
command_env: dict[str, str] | None = None
+ expected_path: str | None = None
if name == "opencode":
# OpenCode: use curl installer (not supported on Windows)
@@ -8010,6 +8311,7 @@ def _install_agent(name: str) -> dict:
return {"ok": False, "message": error, "output": None}
# Use pipefail to ensure curl failures are detected
cmd = _curl_installer_command("https://opencode.ai/install", "bash")
+ expected_path = _native_vendor_install_target(name)
elif name == "claude":
# Claude Code: platform-specific installer
if system == "windows":
@@ -8018,6 +8320,7 @@ def _install_agent(name: str) -> dict:
if error:
return {"ok": False, "message": error, "output": None}
cmd = ["powershell", "-NoProfile", "-Command", "irm https://claude.ai/install.ps1 -ErrorAction Stop | iex"]
+ expected_path = _native_vendor_install_target(name)
else:
# macOS/Linux: use bash with pipefail
for binary in ["curl", "bash"]:
@@ -8025,6 +8328,7 @@ def _install_agent(name: str) -> dict:
if error:
return {"ok": False, "message": error, "output": None}
cmd = _curl_installer_command("https://claude.ai/install.sh", "bash")
+ expected_path = _native_vendor_install_target(name)
elif name == "codex":
# Fresh installs use npm because it is the documented cross-platform
# package source that does not require OS package-manager privileges.
@@ -8032,6 +8336,14 @@ def _install_agent(name: str) -> dict:
if npm_path:
cmd = [npm_path, "install", "-g", "@openai/codex"]
command_env = _codex_npm_install_env(npm_path)
+ if command_env is None:
+ return {
+ "ok": False,
+ "code": "cli_target_unknown",
+ "message": "Codex npm global prefix could not be determined; no installation was started.",
+ "output": None,
+ }
+ expected_path = _declared_codex_npm_target(command_env)
else:
return {
"ok": False,
@@ -8041,7 +8353,10 @@ def _install_agent(name: str) -> dict:
else:
return {"ok": False, "message": f"Unknown agent: {name}", "output": None}
- return _run_install_command(name, cmd, _truncate_output, mode="install", env=command_env)
+ return _run_install_command(
+ name, cmd, _truncate_output, mode="install", env=command_env,
+ expected_path=expected_path,
+ )
def _curl_installer_command(url: str, consumer: str) -> list[str]:
@@ -8199,13 +8514,16 @@ def _run_install_command(
mode: str = "install",
env: dict[str, str] | None = None,
resolve_from: str | None = None,
+ expected_path: str | None = None,
+ preserve_selected_path: str | None = None,
+ readback_validator: Callable[[str], bool] | None = None,
) -> dict:
"""Shared subprocess + post-success bookkeeping for install / upgrade.
Factored out so the self-update branch (existing binary) and the
fresh-install branch (curl/npm bootstrap) share identical post-run
- handling: log the result, invalidate the version cache, capture the
- new install path, and persist it to V2Config when it changed.
+ handling: log the result, verify a fresh executable observation, capture
+ its path, and persist it to V2Config only after verification.
"""
label = "Upgrading" if mode == "upgrade" else "Installing"
try:
@@ -8226,8 +8544,8 @@ def _run_install_command(
signal_process_tree(process, KILL_SIGNAL, logger, f"{name} {mode}")
stdout, stderr = process.communicate(timeout=10)
output = (stdout or "") + ("\n" + stderr if stderr else "")
- # A killed installer can leave the CLI half-replaced; re-probe it.
- _invalidate_version_cache(name)
+ # A killed installer can leave the CLI half-replaced; the next
+ # detection observes it afresh rather than using an old version.
return _install_failure_result(
name,
mode,
@@ -8240,20 +8558,47 @@ def _run_install_command(
result = subprocess.CompletedProcess(cmd, process.returncode, stdout, stderr)
raw_output = (result.stdout + ("\n" + result.stderr if result.stderr else "")).strip()
output = truncate_output(raw_output)
- # Success or failure, the command may have replaced the CLI: the chip
- # refreshes runtime right after this, and must read the new
- # ``--version``, not the 30s-cached value.
- _invalidate_version_cache(name)
+ # Exit zero alone does not certify the executable it left behind.
if result.returncode == 0:
- installed_path = resolve_cli_path(resolve_from or name)
- if installed_path:
- logger.info("Agent %s %s succeeded at %s", name, mode, installed_path)
- else:
- logger.warning(
- "Agent %s %s command succeeded but CLI path was not detected",
- name,
- mode,
- )
+ selected = expected_path if expected_path is not None else resolve_cli_path(resolve_from or name)
+ if expected_path and preserve_selected_path and _is_executable_file(Path(expected_path)):
+ try:
+ # Keep a configured alias only while it still names the
+ # exact artifact at this operation's declared destination.
+ if os.path.samefile(expected_path, preserve_selected_path):
+ selected = preserve_selected_path
+ except OSError:
+ pass
+ # An install must certify its exact destination, never a different
+ # healthy installation found by missing-path fallback.
+ health = None
+ if is_native_cli_backend(name):
+ health = detect_cli(selected, name) if selected else CliHealth(False, None, "missing", reason="not_found").payload()
+ installed_path = health["path"] if health is not None else selected
+ if health is not None and health["status"] != "ok":
+ return {
+ "ok": False,
+ "code": "cli_readback_failed",
+ "message": backend_t("cliHealth.installReadbackFailed", _configured_backend_language()),
+ "path": installed_path,
+ "output": None,
+ "detection": health,
+ }
+ if readback_validator is not None:
+ try:
+ identity_ok = bool(readback_validator(installed_path))
+ except Exception:
+ identity_ok = False
+ if not identity_ok:
+ return {
+ "ok": False,
+ "code": "cli_readback_failed",
+ "message": backend_t("cliHealth.installReadbackFailed", _configured_backend_language()),
+ "path": installed_path,
+ "output": None,
+ "detection": health,
+ }
+ logger.info("Agent %s %s succeeded at %s", name, mode, installed_path)
# Persist real Agent backend CLI paths to V2Config so the next
# ``get_backend_runtime`` reads them directly instead of relying
@@ -8267,7 +8612,10 @@ def _run_install_command(
"message": f"{name} {mode}d successfully" if mode == "install" else f"{name} upgraded successfully",
"path": installed_path,
"output": output,
+ "detection": health,
}
+ if mode == "repair" and result.returncode == 73 and REPAIR_PATH_CONFLICT in raw_output:
+ return _cli_repair_refusal(name, conflict=True)
logger.warning("Agent %s %s failed: %s", name, mode, output)
return _install_failure_result(
name,
@@ -10313,60 +10661,14 @@ def start_dependency_install_job(dep: str) -> dict:
# Backend lifecycle (version probe, latest check, restart)
# =============================================================================
-# The *locally installed* version, keyed by (backend, cli_path) so answers stay
-# tied to the binary they came from. Trade freshness for fewer probes during
-# rapid popover opens. Tuned for human pacing (seconds), not bots.
-#
-# In memory only, deliberately: this answers "what did the binary at this path
-# just print", which a new process can re-measure in milliseconds and which a
-# stale file could get wrong after an install. The *published* version is the
-# expensive one, and :mod:`core.latest_version_cache` persists that instead.
-#
-# The UI server handles requests on multiple threads, so reads, writes, and
-# invalidation can race. A single lock serializes mutation — fast in practice
-# (the cache holds at most a handful of entries), and avoids
-# ``RuntimeError: dictionary changed size during iteration`` during the
-# scan in ``_invalidate_version_cache``.
-_BACKEND_CACHE_LOCK = __import__("threading").Lock()
-_BACKEND_VERSION_CACHE: dict[tuple[str, str], tuple[float, str | None]] = {}
-_BACKEND_VERSION_TTL_SECONDS = 30.0
+# Published registry versions retain their cache; local health/version is one
+# fresh observation because dependencies may change without touching the CLI.
_BACKEND_RUNTIME_USER_AGENT = "avibe/backend-runtime"
_ASKILL_AUTO_UPDATE_ENV = "VIBE_ASKILL_AUTO_UPDATE"
_ASKILL_SKIP_ENV = "VIBE_INSTALL_SKIP_ASKILL"
_TRUTHY_ENV_VALUES = {"1", "true", "yes", "on"}
_FALSY_ENV_VALUES = {"0", "false", "no", "off"}
-def _parse_semver(text: str) -> str | None:
- """Extract the first dotted-numeric version token from *text*.
-
- Handles outputs like ``opencode 1.2.3``, ``codex-cli 0.77.1 (build ...)``
- and ``v1.0.0`` uniformly. Returns ``None`` if no version is found.
- """
- if not text:
- return None
- match = re.search(r"\d+(?:\.\d+){1,3}(?:[-+][\w.\-]+)?", text)
- return match.group(0) if match else None
-
-
-def _probe_cli_version(cli_path: str | None) -> str | None:
- """Run ``<cli> --version`` with a short timeout and return the parsed version."""
- if not cli_path:
- return None
- try:
- result = subprocess.run(
- [cli_path, "--version"],
- capture_output=True,
- text=True,
- timeout=5,
- env=_command_env_for(cli_path if os.path.isabs(cli_path) else None),
- )
- except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as exc:
- logger.debug("CLI version probe failed for %s: %s", cli_path, exc)
- return None
- output = (result.stdout or "") + " " + (result.stderr or "")
- return _parse_semver(output.strip())
-
-
def _http_opener_for_best_effort_probe():
try:
from vibe.proxy import resolve_proxy
@@ -10425,30 +10727,6 @@ def _fetch_latest_version(name: str) -> str | None:
return raw.lstrip("v").strip() or None
-def _cached_version(name: str, cli_path: str | None) -> str | None:
- key = (name, cli_path or "")
- with _BACKEND_CACHE_LOCK:
- cached = _BACKEND_VERSION_CACHE.get(key)
- if cached and time.time() - cached[0] < _BACKEND_VERSION_TTL_SECONDS:
- return cached[1]
- # Probe outside the lock — CLI invocation can block on subprocess for
- # seconds, and we don't want unrelated lookups stuck behind it.
- version = _probe_cli_version(cli_path)
- with _BACKEND_CACHE_LOCK:
- _BACKEND_VERSION_CACHE[key] = (time.time(), version)
- return version
-
-
-def _invalidate_version_cache(name: str) -> None:
- """Drop all cached version entries for *name* across cli paths."""
- with _BACKEND_CACHE_LOCK:
- # Snapshot keys under the lock so the subsequent ``pop`` calls can
- # never observe a partially mutated dict from a concurrent writer.
- stale = [k for k in _BACKEND_VERSION_CACHE if k[0] == name]
- for key in stale:
- _BACKEND_VERSION_CACHE.pop(key, None)
-
-
def _cached_latest(name: str) -> str | None:
return latest_version_cache.cached_latest(name, lambda: _fetch_latest_version(name))
@@ -10720,12 +10998,11 @@ async def get_backend_connection(name: str) -> dict:
enabled = builtin or bool(backend_config.enabled)
supply_mode = config.model_hub.agents[name].mode
native = is_native_cli_backend(name)
- installed = (
- await asyncio.to_thread(resolve_cli_path, backend_config.cli_path or name) is not None
- if native else True
- )
+ cli_health = await detect_cli_async(backend_config.cli_path or name, name) if native else None
+ installed = cli_health["found"] if cli_health is not None else True
result = {
"ok": True, "backend": name, "installed": installed, "enabled": enabled,
+ "cli_status": cli_health["status"] if cli_health is not None else None,
"supply_mode": supply_mode,
"auth": "unknown", "application": "unknown", "ready": False,
"entry_eligible": False,
@@ -10756,7 +11033,7 @@ async def get_backend_connection(name: str) -> dict:
if receipt and not receipt.get("ok") and result["application"] != "stopped":
result["application"] = "failed"
result["message"] = receipt.get("message") or receipt.get("error")
- if not installed or config.load_warnings:
+ if not installed or config.load_warnings or (cli_health is not None and cli_health["status"] != "ok"):
return result
if native and name in await asyncio.to_thread(pending_native_backends, paths.get_state_dir() / "native-takeover"):
return result
@@ -10811,27 +11088,33 @@ async def get_backend_connection(name: str) -> dict:
return result
-def get_backend_runtime(name: str) -> dict:
- """Return live lifecycle info for one backend.
+def get_backend_runtime(name: str, cli_path: str | None = None) -> dict:
+ """Synchronous non-HTTP entry; the HTTP route awaits the same owner."""
+ return asyncio.run(get_backend_runtime_async(name, cli_path))
+
- Versions are cached for short windows so popovers and re-renders do not
- fan out into many CLI invocations or registry HTTP calls.
+async def get_backend_runtime_async(name: str, cli_path: str | None = None) -> dict:
+ """Lifecycle projection bound to the selected path's fresh CLI observation.
+
+ Registry lookups retain their cache. Health is not cached by launcher stat:
+ replacing an npm platform package can leave that stat entirely unchanged.
"""
if not is_native_cli_backend(name):
return {"ok": False, "error": f"Unknown backend: {name}"}
try:
- config = V2Config.load()
+ config = await asyncio.to_thread(V2Config.load)
except Exception as exc:
logger.debug("Failed to load config for backend runtime: %s", exc)
config = None
backend_cfg = getattr(getattr(config, "agents", None), name, None) if config else None
enabled = bool(getattr(backend_cfg, "enabled", False))
- configured_path = getattr(backend_cfg, "cli_path", "") or name
+ configured_path = (cli_path or name) if cli_path is not None else (getattr(backend_cfg, "cli_path", "") or name)
- resolved_path = resolve_cli_path(configured_path)
- installed = resolved_path is not None
+ health = await detect_cli_async(configured_path, name)
+ resolved_path = health["path"]
+ installed = health["found"]
private_backend = resolved_path is not None and is_desktop_backend_path(resolved_path)
legacy_bundled_codex = (
name == "codex"
@@ -10844,14 +11127,14 @@ def get_backend_runtime(name: str) -> dict:
else None
)
- current_version = _cached_version(name, resolved_path) if installed else None
- latest_version = None if legacy_bundled_codex else _cached_latest(name)
+ current_version = health["version"]
+ latest_version = None if legacy_bundled_codex else await asyncio.to_thread(_cached_latest, name)
has_update = _compare_versions(current_version, latest_version)
if name == "opencode":
- process_status = _opencode_process_status() if installed else "stopped"
+ process_status = await asyncio.to_thread(_opencode_process_status) if installed else "stopped"
elif name == "codex":
- process_status = _codex_process_status(resolved_path) if installed else "stopped"
+ process_status = await asyncio.to_thread(_codex_process_status, resolved_path) if installed else "stopped"
elif name == "claude":
process_status = "unknown"
else:
@@ -10865,6 +11148,8 @@ def get_backend_runtime(name: str) -> dict:
"cli_path": configured_path,
"resolved_path": resolved_path,
"installed": installed,
+ "status": health["status"],
+ "reason": health["reason"],
"current_version": current_version,
"latest_version": latest_version,
"has_update": has_update,
@@ -11029,7 +11314,6 @@ def _restart_backend(name: str, *, metadata: Optional[dict[str, Any]] = None) ->
return {"ok": True, "apply_on_next_start": True, "message": backend_t("backendConnection.applyOnStart", lang=language)}
controller_handled, controller_error = _request_controller_restart(name, metadata=metadata)
- _invalidate_version_cache(name)
if controller_handled:
if controller_error:
diff --git a/vibe/cli.py b/vibe/cli.py
index 0fb8ad37a..42d02eb04 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -13006,8 +13006,9 @@ def _doctor(*, deep: bool = False):
label = display_name_for_backend(backend)
if backend_config.enabled:
cli_path = backend_config.cli_path
- found_path = api.detect_cli(cli_path).get("path") if cli_path else None
- if found_path:
+ detection = api.detect_cli(cli_path or backend, backend)
+ found_path = detection.get("path")
+ if detection.get("status") == "ok":
_add_doctor_item(
agent_items,
"pass",
@@ -13018,7 +13019,7 @@ def _doctor(*, deep: bool = False):
_add_doctor_item(
agent_items,
"warn",
- i18n_t("doctor.item.agentCliMissing", language, agent=label, path=cli_path),
+ i18n_t("doctor.item.agentCliUnhealthy" if detection.get("found") else "doctor.item.agentCliMissing", language, agent=label, path=cli_path),
i18n_t("doctor.action.agentCliMissing", language, agent=label),
)
summary["warn"] += 1
diff --git a/vibe/cli_health.py b/vibe/cli_health.py
new file mode 100644
index 000000000..2cb406f35
--- /dev/null
+++ b/vibe/cli_health.py
@@ -0,0 +1,106 @@
+"""Native CLI version evidence, shared by detection and install verification.
+
+This is executable health, not authentication or overall backend readiness.
+Only the normalized version and a closed reason code leave the probe; child
+output is bounded, used for recognition and never becomes a UI diagnostic.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import re
+from dataclasses import asdict, dataclass
+from typing import Literal, Mapping
+
+from core.command_runner import SupervisedCommandStartupError, run_supervised_command
+
+CliStatus = Literal["ok", "broken", "missing", "unknown"]
+PROBE_TIMEOUT_SECONDS = 5.0
+PROBE_OUTPUT_BYTES = 8192
+_VERSION = r"\d+\.\d+\.\d+(?:\.\d+)?(?:-[\w.-]+)?(?:\+[\w.-]+)?"
+_VERSION_PATTERNS = {
+ "claude": rf"(?:({_VERSION})\s+\(Claude Code\)|(?:Claude Code|claude)\s+({_VERSION}))",
+ "codex": rf"(?:codex-cli|codex)\s+({_VERSION})(?:\s+\(build [^\r\n]+\))?",
+ "opencode": rf"(?:opencode\s+)?({_VERSION}|dev|local)",
+}
+
+
+@dataclass(frozen=True)
+class CliHealth:
+ found: bool
+ path: str | None
+ status: CliStatus
+ version: str | None = None
+ reason: str | None = None
+
+ def payload(self) -> dict:
+ return asdict(self)
+
+
+def cli_version(backend: str, stdout: str | None, stderr: str | None) -> str | None:
+ """Recognize a complete CLI version response, not a crash's first semver.
+
+ OpenCode prints a bare version or a final version after informational
+ refresh lines; Claude and Codex identify themselves. Warnings on stderr do
+ not replace a successful stdout version.
+ """
+ pattern = _VERSION_PATTERNS.get(backend)
+ if pattern is None:
+ return None
+ text = (stdout or "").strip() or (stderr or "").strip()
+ if backend == "opencode":
+ lines = [line.strip() for line in text.splitlines() if line.strip()]
+ if len(lines) > 1 and all(line.startswith("INFO ") for line in lines[:-1]):
+ text = lines[-1]
+ match = re.fullmatch(pattern, text, flags=re.IGNORECASE)
+ if not match:
+ return None
+ return next(value for value in match.groups() if value is not None)
+
+
+async def probe_cli(
+ backend: str,
+ path: str,
+ *,
+ env: Mapping[str, str],
+ timeout_seconds: float = PROBE_TIMEOUT_SECONDS,
+) -> CliHealth:
+ if backend not in _VERSION_PATTERNS:
+ return CliHealth(True, path, "unknown", reason="unsupported_backend")
+ # The same supplier as native backend launches owns app-private helpers
+ # (notably Codex's support binaries); a generic PATH is not equivalent.
+ from vibe.desktop_backends import DesktopBackendError, desktop_backend_subprocess_environment
+ from vibe.upgrade import get_safe_cwd
+
+ try:
+ env = desktop_backend_subprocess_environment(backend, path, env) or env
+ except DesktopBackendError:
+ return CliHealth(True, path, "broken", reason="invalid_installation")
+ try:
+ result = await run_supervised_command(
+ command=[path, "--version"],
+ cwd=get_safe_cwd(),
+ env=env,
+ timeout_seconds=timeout_seconds,
+ max_output_bytes=PROBE_OUTPUT_BYTES,
+ label=f"{backend} CLI health",
+ hide_console=True,
+ )
+ except (OSError, SupervisedCommandStartupError):
+ # Failure to start our supervisor is not proof about the selected CLI.
+ return CliHealth(True, path, "unknown", reason="probe_unavailable")
+ if result.timed_out:
+ return CliHealth(True, path, "broken", reason="probe_timeout")
+ if result.exit_code != 0:
+ return CliHealth(True, path, "broken", reason="probe_failed")
+ if result.stdout_truncated or result.stderr_truncated:
+ return CliHealth(True, path, "broken", reason="invalid_version")
+ version = cli_version(backend, result.stdout, result.stderr)
+ if version is None:
+ return CliHealth(True, path, "broken", reason="invalid_version")
+ return CliHealth(True, path, "ok", version=version)
+
+
+def probe_cli_sync(backend: str, path: str, *, env: Mapping[str, str]) -> CliHealth:
+ """Adapter for synchronous CLI/installer workers; HTTP awaits probe_cli."""
+ return asyncio.run(probe_cli(backend, path, env=env))
diff --git a/vibe/cli_paths.py b/vibe/cli_paths.py
index 727a21cbc..250e5f0ed 100644
--- a/vibe/cli_paths.py
+++ b/vibe/cli_paths.py
@@ -14,6 +14,62 @@ from vibe.desktop_backends import is_desktop_backend_path, resolve_published_des
logger = logging.getLogger(__name__)
+def _ordered_cli_candidates(
+ binary: str,
+ *,
+ include_npm_global: bool,
+ candidate_paths=None,
+) -> list[Path]:
+ """Return one ordered candidate list for runnable and presence-only probes.
+
+ The order is deliberately shared by both consumers: standard locations,
+ the active ``PATH``, then the active npm-global locations. A non-executable
+ earlier candidate therefore remains visible to presence-only health checks,
+ while runnable resolution still selects the first executable later in the
+ same sequence.
+ """
+ if not binary:
+ return []
+
+ candidate_paths = candidate_paths or _candidate_cli_paths
+ expanded = Path(os.path.expanduser(binary))
+ has_path_separator = os.sep in binary or (os.altsep is not None and os.altsep in binary)
+ candidates: list[Path] = []
+
+ def add(candidate: Path) -> None:
+ if candidate not in candidates:
+ candidates.append(candidate)
+
+ # Explicit paths are never redirected through PATH or npm-global discovery.
+ for candidate in candidate_paths(binary, include_npm_global=False):
+ add(candidate)
+ if expanded.is_absolute() or has_path_separator:
+ return candidates
+
+ # shutil.which preserves the platform's executable lookup semantics and
+ # gives us the first runnable PATH result. Raw PATH entries follow so a
+ # non-executable file can still be reported as a broken, present candidate.
+ path_match = shutil.which(os.path.expanduser(binary))
+ if path_match:
+ add(Path(path_match))
+ for entry in os.environ.get("PATH", "").split(os.pathsep):
+ if not entry:
+ continue
+ path_candidates = [Path(entry) / binary]
+ if os.name == "nt":
+ path_candidates = _windows_executable_candidates(path_candidates)
+ for candidate in path_candidates:
+ add(candidate)
+
+ if include_npm_global and not any(_is_executable_file(candidate) for candidate in candidates):
+ # Defer the npm-prefix subprocess until standard and PATH candidates
+ # have all failed the executable check. This keeps healthy local CLIs
+ # from paying the npm query timeout on every health probe.
+ for candidate in candidate_paths(binary, include_npm_global=True):
+ add(candidate)
+ return candidates
+
+
def _is_executable_file(path: Path) -> bool:
return path.exists() and path.is_file() and os.access(path, os.X_OK)
@@ -217,18 +273,13 @@ def _resolve_cli_path_once(
) -> str | None:
candidate_paths = candidate_paths or _candidate_cli_paths
is_executable_file = is_executable_file or _is_executable_file
- for candidate in candidate_paths(binary, include_npm_global=False):
+ for candidate in _ordered_cli_candidates(
+ binary,
+ include_npm_global=include_npm_global,
+ candidate_paths=candidate_paths,
+ ):
if is_executable_file(candidate):
return str(candidate)
-
- path = shutil.which(os.path.expanduser(binary)) if binary else None
- if path:
- return path
-
- if include_npm_global:
- for candidate in _npm_global_binary_candidates(binary):
- if _is_executable_file(candidate):
- return str(candidate)
return None
diff --git a/vibe/cli_repair.py b/vibe/cli_repair.py
new file mode 100644
index 000000000..cb25bbe82
--- /dev/null
+++ b/vibe/cli_repair.py
@@ -0,0 +1,99 @@
+"""Recognize existing CLI installation provenance without executing that CLI.
+
+Unknown sources are not invitations to migrate an installation. These plans
+only cover package layouts or canonical native destinations we can identify.
+The installer owner executes them under its existing lock and reads back the
+exact destination with its normal (unmasked) launch environment.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from dataclasses import dataclass
+from pathlib import Path
+
+PACKAGES = {"claude": "@anthropic-ai/claude-code", "opencode": "opencode-ai", "codex": "@openai/codex"}
+BREW_NAMES = {"claude": "claude-code", "opencode": "opencode", "codex": "codex"}
+REPAIR_PATH_CONFLICT = "avibe: repair blocked by another resolvable opencode"
+
+
+@dataclass(frozen=True)
+class RepairSource:
+ kind: str
+ destination: str
+ package: str | None = None
+ prefix: Path | None = None
+ cask: bool = False
+
+
+def identify_repair_source(backend: str, selected: str, *, home: Path | None = None) -> RepairSource | None:
+ if backend not in PACKAGES:
+ return None
+ home = home or Path.home()
+ original = Path(selected).expanduser().absolute()
+ try:
+ target = original.resolve()
+ package = PACKAGES[backend]
+ package_parts = Path(package).parts
+ if os.name == "nt" and original.name.lower() == backend + ".cmd":
+ manifest = original.parent / "node_modules" / package / "package.json"
+ if manifest.is_file() and manifest.stat().st_size < 65536 and original.stat().st_size < 16384:
+ wrapper = original.read_text(encoding="utf-8").replace("\\", "/").lower()
+ if ("%~dp0" in wrapper or "%dp0%" in wrapper) and "node_modules/" + package in wrapper:
+ if json.loads(manifest.read_text(encoding="utf-8")).get("name") == package:
+ return RepairSource("npm", str(original), package, original.parent)
+ for directory in target.parents:
+ if tuple(directory.parts[-len(package_parts) :]) != package_parts:
+ continue
+ modules = directory.parents[len(package_parts) - 1]
+ if modules.name != "node_modules":
+ continue
+ manifest = directory / "package.json"
+ if not manifest.is_file() or manifest.stat().st_size >= 65536:
+ return None
+ if json.loads(manifest.read_text(encoding="utf-8")).get("name") != package:
+ return None
+ if modules.parent.name == "lib":
+ prefix = modules.parent.parent
+ elif os.name == "nt" and original.parent == modules.parent:
+ prefix = modules.parent
+ else:
+ # A project-local npm install is not an npm-global prefix.
+ return None
+ return RepairSource("npm", str(original), package, prefix)
+ for root in target.parents:
+ if root.name not in {"Cellar", "Caskroom"}:
+ continue
+ relative = target.relative_to(root)
+ if relative.parts[0] != BREW_NAMES[backend]:
+ return None
+ return RepairSource("brew", str(original), BREW_NAMES[backend], root.parent, root.name == "Caskroom")
+ if backend == "claude":
+ native = home / ".local" / "bin" / ("claude.exe" if os.name == "nt" else "claude")
+ versions = home / ".local" / "share" / "claude" / "versions"
+ if original == native and (not original.is_symlink() or target.is_relative_to(versions)):
+ return RepairSource("native", str(native))
+ if backend == "opencode" and original == home / ".opencode" / "bin" / "opencode":
+ if not original.is_symlink() or target.parent == original.parent:
+ return RepairSource("native", str(original))
+ except (OSError, ValueError, TypeError, AttributeError):
+ return None
+ return None
+
+
+def native_bootstrap_env(env: dict[str, str], *, hide_directory: Path | None = None) -> dict[str, str]:
+ """No shell startup hooks/functions may reintroduce the hidden old CLI."""
+ result = {
+ k: v
+ for k, v in env.items()
+ if k not in {"BASH_ENV", "ENV", "SHELLOPTS", "BASHOPTS"} and not k.startswith("BASH_FUNC_")
+ }
+ if hide_directory is not None:
+ hidden = hide_directory.resolve()
+ result["PATH"] = os.pathsep.join(
+ entry
+ for entry in result.get("PATH", "").split(os.pathsep)
+ if Path(entry or os.curdir).expanduser().resolve() != hidden
+ )
+ return result
diff --git a/vibe/desktop_backends.py b/vibe/desktop_backends.py
index ed77f1241..35c977451 100644
--- a/vibe/desktop_backends.py
+++ b/vibe/desktop_backends.py
@@ -24,6 +24,7 @@ import psutil
from config import paths
from config.atomic_io import write_atomic
+from vibe.cli_health import cli_version
from core.process_isolation import (
KILL_SIGNAL,
PROCESS_IDENTITY_ENV,
@@ -1218,7 +1219,7 @@ def _verify_backend_executable(
f"Installed {backend} executable could not be started.",
code="executable_probe_failed",
) from exc
- if result.returncode != 0 or not _version_from_output(result.stdout, result.stderr):
+ if result.returncode != 0 or not cli_version(backend, result.stdout, result.stderr):
raise DesktopBackendError(
f"Installed {backend} executable did not report a valid version.",
code="executable_probe_failed",
@@ -1383,13 +1384,6 @@ def _remove_internal_directory(path: Path, root: Path) -> None:
shutil.rmtree(path)
-def _version_from_output(stdout: str | None, stderr: str | None) -> str | None:
- import re
-
- match = re.search(r"\d+(?:\.\d+){1,3}(?:[-+][\w.-]+)?", f"{stdout or ''} {stderr or ''}")
- return match.group(0) if match else None
-
-
def _bounded_output(stdout: str | None, stderr: str | None) -> str | None:
output = (stdout or "") + ("\n" + stderr if stderr else "")
output = output.strip()
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 035f4280f..933db74d0 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -1074,6 +1074,11 @@
"stopRefused": "Nothing was stopped: this command runs from a desktop-managed Avibe Runtime, and the running {part} is not that Runtime's ({reason}). Stop it from the Avibe that started it.",
"restartRefused": "Nothing was restarted: this command runs from a desktop-managed Avibe Runtime, and the running {part} is not that Runtime's ({reason}). Restart it from the Avibe that started it."
},
+ "cliHealth": {
+ "installReadbackFailed": "The installer finished, but the selected CLI is missing or cannot run. Installation was not verified; repair it and try again.",
+ "repairUnavailable": "Avibe could not safely identify a supported repair source for {backend}. Reinstall it with its original installer or select the correct CLI path; no installation was changed.",
+ "repairPathConflict": "Another OpenCode command is still visible in the repair environment. Repair was not started. Remove the conflicting PATH entry or reinstall OpenCode with its original installer."
+ },
"agentInstall": {
"installFailed": "Could not install {backend}.",
"upgradeFailed": "Could not upgrade {backend}.",
@@ -1518,6 +1523,7 @@
"slackConfigMissing": "Cannot check Slack: configuration not loaded",
"agentCliFound": "{agent} CLI found: {path}",
"agentCliMissing": "{agent} CLI not found: {path}",
+ "agentCliUnhealthy": "{agent} CLI is present but could not be verified as runnable: {path}",
"agentDisabled": "{agent}: disabled",
"defaultAgent": "Default Agent: {agent}",
"agentConfigMissing": "Cannot check agents: configuration not loaded",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 9e96ad6e0..8c120f176 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -1074,6 +1074,11 @@
"stopRefused": "未停止任何进程:此命令来自桌面托管的 Avibe Runtime,而正在运行的 {part} 不属于该 Runtime({reason})。请从启动它的 Avibe 停止它。",
"restartRefused": "未重启任何进程:此命令来自桌面托管的 Avibe Runtime,而正在运行的 {part} 不属于该 Runtime({reason})。请从启动它的 Avibe 重启它。"
},
+ "cliHealth": {
+ "installReadbackFailed": "安装程序已结束,但所选 CLI 仍然缺失或无法运行,尚未验证安装成功。请修复后重试。",
+ "repairUnavailable": "Avibe 无法安全确定 {backend} 的原安装来源或修复方式。请使用原安装工具重新安装,或选择正确的 CLI 路径;本次未修改任何安装。",
+ "repairPathConflict": "修复环境中仍能找到另一个 OpenCode 命令,本次未开始修复。请移除冲突的 PATH 项,或使用原安装工具重新安装 OpenCode。"
+ },
"agentInstall": {
"installFailed": "无法安装 {backend}。",
"upgradeFailed": "无法升级 {backend}。",
@@ -1518,6 +1523,7 @@
"slackConfigMissing": "无法检查 Slack:配置尚未加载",
"agentCliFound": "找到 {agent} CLI:{path}",
"agentCliMissing": "找不到 {agent} CLI:{path}",
+ "agentCliUnhealthy": "{agent} CLI 文件存在,但未能验证其可运行:{path}",
"agentDisabled": "{agent}:已禁用",
"defaultAgent": "默认 Agent:{agent}",
"agentConfigMissing": "无法检查 Agent:配置尚未加载",
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index f35bab263..f3be8be65 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1394,6 +1394,11 @@ def _is_direct_loopback_connection() -> bool:
return not _has_forwarded_metadata() and _is_loopback_peer() and _is_loopback_host(request.host)
+def _same_origin_browser_request() -> bool:
+ source = _request_origin(request.headers.get("Origin")) or _request_origin(request.headers.get("Referer"))
+ return bool(source and _same_origin(source, request.host_url.rstrip("/")))
+
+
def _is_direct_loopback_browser_request() -> bool:
"""Strict same-origin browser admission for local author attribution.
@@ -1402,25 +1407,25 @@ def _is_direct_loopback_browser_request() -> bool:
directly connected over loopback and present a same-origin header.
"""
- if not _is_direct_loopback_connection():
- return False
- origin = _request_origin(request.headers.get("Origin")) or _request_origin(request.headers.get("Referer"))
- return bool(origin and _same_origin(origin, request.host_url.rstrip("/")))
+ return _is_direct_loopback_connection() and _same_origin_browser_request()
def _trusted_browser_author_key() -> str | None:
"""Resolve the authenticated browser author for local or remote requests.
- Direct loopback keeps the install-local identity. Remote browser access is
- admitted only through the configured Avibe Cloud origin with a valid signed
- session cookie; LAN and arbitrary proxy routes remain closed. Reads require
- the same origin evidence as mutations so a remote session cookie cannot be
- used as a cross-origin data oracle.
+ Direct loopback and configured private setup-host browser access keep the
+ install-local identity when same-origin evidence is present. Remote browser
+ access is admitted only through the configured Avibe Cloud origin with a
+ valid signed session cookie; arbitrary proxy routes remain closed. Reads
+ require the same origin evidence as mutations so a remote session cookie
+ cannot be used as a cross-origin data oracle.
"""
if _is_direct_loopback_browser_request():
return "avibe:local"
config = _load_remote_access_config()
+ if config is not None and _is_setup_host_request(config) and _same_origin_browser_request():
+ return "avibe:local"
if config is None or not _is_remote_access_request(config):
return None
source = _request_origin(request.headers.get("Origin")) or _request_origin(
@@ -7031,12 +7036,21 @@ def web_push_test():
)
[email protected]("/api/cli/detect")
-def cli_detect():
- from vibe import api
[email protected]("/api/cli/detect", include_in_schema=False)
+async def cli_detect(starlette_request: FastAPIRequest):
+ async def handler():
+ from vibe import api
- binary = request.args.get("binary", "")
- return jsonify(api.detect_cli(binary))
+ backend = request.args.get("backend")
+ if backend is not None and backend not in NATIVE_CLI_BACKENDS:
+ return jsonify({"ok": False, "error": "unsupported_backend"}), 400
+ if _trusted_browser_author_key() is None:
+ return jsonify({"ok": False, "error": "same_origin_required"}), 403
+ response = jsonify(await api.detect_cli_async(request.args.get("binary", ""), backend))
+ response.headers["Cache-Control"] = "private, no-store"
+ return response
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
@app.route("/api/slack/manifest")
@@ -8481,15 +8495,20 @@ async def backend_connection(name: str, starlette_request: FastAPIRequest):
return await _dispatch_native_ui_request(starlette_request, handler)
[email protected]("/api/backend/<name>/runtime")
-def backend_runtime(name):
- """Return lifecycle info (version, update, process status) for a backend."""
- if name not in NATIVE_CLI_BACKENDS:
- return jsonify({"ok": False, "error": f"Unknown backend: {name}"}), 400
[email protected]("/api/backend/{name}/runtime", include_in_schema=False)
+async def backend_runtime(name: str, starlette_request: FastAPIRequest):
+ async def handler():
+ if name not in NATIVE_CLI_BACKENDS:
+ return jsonify({"ok": False, "error": "unsupported_backend"}), 400
+ if _trusted_browser_author_key() is None:
+ return jsonify({"ok": False, "error": "same_origin_required"}), 403
+ from vibe import api
- from vibe import api
+ response = jsonify(await api.get_backend_runtime_async(name, request.args.get("cli_path")))
+ response.headers["Cache-Control"] = "private, no-store"
+ return response
- return jsonify(api.get_backend_runtime(name))
+ return await _dispatch_native_ui_request(starlette_request, handler)
@app.route("/api/backend/<name>/restart", methods=["POST"])