Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(model-hub): keep Agent reads off CLI discovery (#1715)
Call White0f1e60d2e4a7
diff --git a/core/controller.py b/core/controller.pyindex 372882dd2..545705c1d 100644--- a/core/controller.py+++ b/core/controller.py@@ -417,7 +417,7 @@ class Controller:def _init_model_hub(self) -> None:"""Create the Model Hub aggregate only for an explicit release opt-in."""- from config.v2_config import is_model_hub_enabled+ from config.v2_config import V2Config, is_model_hub_enabledself.model_hub_service = Noneself.model_hub_turn_gateway = None@@ -430,6 +430,7 @@ class Controller:from core.handlers.model_hub import create_default_servicefrom core.handlers.model_hub.turn_gateway import ModelHubTurnGatewayfrom modules.agents.model_hub import ModelHubRuntimeRouter+ from vibe.api import resolve_cli_pathsdef default_vibe_agent_model(backend: str) -> Optional[str]:agent = self.vibe_agent_store.get_default_agent()@@ -454,25 +455,42 @@ class Controller:def cli_present(backend: str) -> bool:# Payload assembly runs on the controller loop. Read only the last- # worker-produced snapshot here; a missing/erroring probe is false.+ # complete worker-produced snapshot here.return cli_presence.get(backend, False)- def refresh_cli_presence() -> None:- from config.v2_config import V2Config- from vibe.api import resolve_cli_path-+ def refresh_cli_presence(include_npm_global: bool) -> None:+ nonlocal cli_presencetry:v2_config = V2Config.load()except FileNotFoundError:v2_config = None+ except Exception:+ logger.warning("Model Hub CLI config probe failed", exc_info=True)+ v2_config = None+ configured_paths: dict[str, str] = {}for backend in ("claude", "codex", "opencode"):backend_config = getattr(getattr(v2_config, "agents", None), backend, None)- configured_path = getattr(backend_config, "cli_path", None) or backend- try:- cli_presence[backend] = resolve_cli_path(str(configured_path)) is not None- except Exception:- logger.warning("Model Hub CLI presence probe failed for %s", backend, exc_info=True)- cli_presence[backend] = False+ configured_paths[backend] = str(+ getattr(backend_config, "cli_path", None) or backend+ )+ try:+ resolved_paths = resolve_cli_paths(+ list(configured_paths.values()),+ include_npm_global=include_npm_global,+ )+ except Exception:+ logger.warning("Model Hub CLI presence probe failed", exc_info=True)+ return+ refreshed = {+ backend: resolved_paths.get(configured_path) is not None+ for backend, configured_path in configured_paths.items()+ }+ cli_presence = refreshed++ # Seed only filesystem and PATH facts before the internal RPC surface+ # exists. The page publishes npm-only installs through an explicit+ # post-paint refresh, so controller readiness never waits on npm.+ refresh_cli_presence(False)self.model_hub_service = create_default_service(requested_model_override=default_vibe_agent_model,diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.pyindex 7838c7f6c..bc75fcdfc 100644--- a/core/handlers/model_hub/rpc.py+++ b/core/handlers/model_hub/rpc.py@@ -4,15 +4,48 @@ from __future__ import annotationsimport asynciofrom typing import Any+from weakref import WeakKeyDictionaryfrom .service import ModelHubError, ModelHubServicefrom .usage import USAGE_DEFAULT_WINDOW_DAYS+_cli_presence_refresh_tasks: WeakKeyDictionary[+ ModelHubService,+ asyncio.Task[None],+] = WeakKeyDictionary()+async def _refresh_agent_presence(service: ModelHubService) -> None:"""Refresh host CLI facts without blocking the controller event loop."""- await asyncio.to_thread(service.refresh_cli_presence)+ current = _cli_presence_refresh_tasks.get(service)+ if current is not None and not current.done():+ await asyncio.shield(current)+ return++ task = _start_agent_presence_refresh(service)+ await asyncio.shield(task)+++async def _run_agent_presence_refresh(service: ModelHubService) -> None:+ try:+ await asyncio.to_thread(+ service.refresh_cli_presence,+ include_npm_global=True,+ )+ finally:+ current = asyncio.current_task()+ if _cli_presence_refresh_tasks.get(service) is current:+ _cli_presence_refresh_tasks.pop(service, None)+++def _start_agent_presence_refresh(service: ModelHubService) -> asyncio.Task[None]:+ task = asyncio.create_task(+ _run_agent_presence_refresh(service),+ name="model-hub-cli-presence-refresh",+ )+ _cli_presence_refresh_tasks[service] = task+ return taskasync def dispatch_model_hub_rpc(@@ -53,10 +86,14 @@ async def dispatch_model_hub_rpc(confirmed_interruptions=payload.get("would_interrupt"),)if operation == "list_agents":+ if payload.get("refresh_cli_presence") is True:+ await _refresh_agent_presence(service)return await asyncio.to_thread(service.list_agents)if operation == "get_agent_sources":- await _refresh_agent_presence(service)- return service.get_agent_sources(payload.get("backend"))+ return await asyncio.to_thread(+ service.get_agent_sources,+ payload.get("backend"),+ )if operation == "set_agent_sources":await _refresh_agent_presence(service)return await service.set_agent_sources(diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex df2fa18bf..5954c2b69 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -583,7 +583,7 @@ class ModelHubService:Callable[[BackendName], list[tuple[str, Optional[str]]]]] = None,cli_present_override: Optional[Callable[[BackendName], bool]] = None,- cli_presence_refresh: Optional[Callable[[], None]] = None,+ cli_presence_refresh: Optional[Callable[[bool], None]] = None,now: Callable[[], datetime] = _utc_now,):self.store = store@@ -3420,15 +3420,14 @@ class ModelHubService:}def list_agents(self) -> list[dict]:- self.refresh_cli_presence()config = self.store.load()return [self._agent_payload(config, config.agents[backend]) for backend in ("claude", "codex", "opencode")]- def refresh_cli_presence(self) -> None:+ def refresh_cli_presence(self, *, include_npm_global: bool = False) -> None:if self.cli_presence_refresh is None:returntry:- self.cli_presence_refresh()+ self.cli_presence_refresh(include_npm_global)except Exception:logger.warning("Model Hub CLI presence refresh failed", exc_info=True)@@ -5477,7 +5476,7 @@ def create_default_service(Callable[[BackendName], list[tuple[str, Optional[str]]]]] = None,cli_present_override: Optional[Callable[[BackendName], bool]] = None,- cli_presence_refresh: Optional[Callable[[], None]] = None,+ cli_presence_refresh: Optional[Callable[[bool], None]] = None,) -> ModelHubService:if adapter is None:from vibe.model_hub_runtime import get_model_hub_engine_adapterdiff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 47dfe6a6b..fac22e655 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -35,7 +35,7 @@ compatibility path.| POST `/api/models/sources/<source_id>/models` | `{model_id, display_name?, reasoning_efforts}` → `{source: Source}` | Creates one user-authored model entry. The Source identity comes only from the path. || PATCH `/api/models/sources/<source_id>/models/<model_id>` | `{reasoning_efforts}` → `{source: Source}` | Replaces the complete capability list on either model origin without changing identity, origin, or Routes. || DELETE `/api/models/sources/<source_id>/models/<model_id>` | `{force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or Source-mutation success | Deletes a manual entry; for a discovered entry it persists `retired: true` without deleting the row. Both outcomes use the same exact-hop and supply guards. |-| GET `/api/models/agents` | → `{agents: AgentSupply[]}` | Backend records include server-authoritative `cli_present` and `named_agents`, the enabled named-Agent live projection. |+| GET `/api/models/agents` | → `{agents: AgentSupply[]}` | Backend records include server-authoritative `cli_present` and `named_agents`, the enabled named-Agent live projection. The default read returns the current presence snapshot; `?refresh_cli_presence=1` first refreshes deep npm-only discovery and returns the resulting snapshot. || GET `/api/models/agents/<backend>/sources` | → `{agent: AgentSupply}` | Returns the authoritative effective order and eligibility. || PUT `/api/models/agents/<backend>/sources` | `{order: string[]}` → `{agent: AgentSupply}` | Stores and re-echoes the complete canonical order; no policy state exists. This route never touches a Route chain and has no guarded `409` branch. || POST `/api/models/agents/<backend>/chains/reorder` | → `{agent: AgentSupply}` | Idempotently reorders every stored Route by the current Source order without adding, removing, remapping, matching, or guarding. The total order is defined below. |diff --git a/tests/test_controller_model_hub_gate.py b/tests/test_controller_model_hub_gate.pyindex 0f8d8cc73..6275312a6 100644--- a/tests/test_controller_model_hub_gate.py+++ b/tests/test_controller_model_hub_gate.py@@ -37,6 +37,7 @@ def test_controller_builds_one_model_hub_aggregate_after_explicit_opt_in(monkeypimport core.handlers.model_hub as model_hubimport core.handlers.model_hub.turn_gateway as turn_gatewayimport modules.agents.model_hub as agent_model_hub+ from vibe import apiservice = object()calls = []@@ -63,6 +64,19 @@ def test_controller_builds_one_model_hub_aggregate_after_explicit_opt_in(monkeypmonkeypatch.setattr(model_hub, "create_default_service", create_service)monkeypatch.setattr(turn_gateway, "ModelHubTurnGateway", Gateway)monkeypatch.setattr(agent_model_hub, "ModelHubRuntimeRouter", Router)+ presence_probes = []+ probe_failure = [False]++ def resolve_cli_paths(binaries, *, include_npm_global=True):+ presence_probes.append((binaries, include_npm_global))+ if probe_failure[0]:+ raise OSError("CLI inventory unavailable")+ return {+ binary: f"/usr/bin/{binary}" if binary == "codex" else None+ for binary in binaries+ }++ monkeypatch.setattr(api, "resolve_cli_paths", resolve_cli_paths)controller = Controller.__new__(Controller)controller.config = SimpleNamespace(language="zh")controller.vibe_agent_store = SimpleNamespace(@@ -80,6 +94,13 @@ def test_controller_builds_one_model_hub_aggregate_after_explicit_opt_in(monkeypassert controller.model_hub_runtime.turn_gateway is controller.model_hub_turn_gatewayassert captured["requested_model_override"]("codex") == "agent-model"assert captured["requested_model_override"]("claude") is None+ assert captured["cli_present_override"]("codex") is True+ assert captured["cli_present_override"]("claude") is False+ assert presence_probes == [(["claude", "codex", "opencode"], False)]+ probe_failure[0] = True+ captured["cli_presence_refresh"](True)+ assert captured["cli_present_override"]("codex") is True+ assert presence_probes[-1] == (["claude", "codex", "opencode"], True)assert controller.model_hub_turn_gateway.language_provider() == "zh"assert calls == [("gateway", service, controller.model_hub_turn_gateway.language_provider),diff --git a/tests/test_local_deps.py b/tests/test_local_deps.pyindex 01606f111..2b87f29ff 100644--- a/tests/test_local_deps.py+++ b/tests/test_local_deps.py@@ -89,7 +89,7 @@ def _installable_avault_release(raise AssertionError(f"unexpected url: {url}")monkeypatch.setattr(api.urllib.request, "urlopen", fake_urlopen)- def fake_candidate_cli_paths(binary: str):+ def fake_candidate_cli_paths(binary: str, *, include_npm_global: bool = True):expanded = api.Path(api.os.path.expanduser(binary))has_path_separator = api.os.sep in binary or (api.os.altsep is not None and api.os.altsep in binary)if expanded.is_absolute() or has_path_separator:diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex a0bf202ef..86c19aa9e 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -1875,6 +1875,20 @@ def test_agents_endpoint_projects_cli_presence_from_runtime(tmp_path):}+def test_agents_collection_reads_cli_presence_without_running_discovery(tmp_path):+ service, _store, _adapter = _service(tmp_path)+ calls = []+ service.cli_presence_refresh = lambda include_npm_global: calls.append(+ include_npm_global+ )+ service.cli_present_override = lambda backend: backend == "codex"++ agents = {agent["backend"]: agent for agent in service.list_agents()}++ assert agents["codex"]["cli_present"] is True+ assert calls == []++def test_agents_endpoint_projects_exact_chain_runnability(tmp_path):service, store, _adapter = _service(tmp_path)model_id = "claude-opus-4-6"@@ -1972,24 +1986,149 @@ def test_agents_endpoint_cli_presence_probe_errors_fail_closed(tmp_path):assert all(agent["cli_present"] is False for agent in agents.values())-def test_agent_supply_rpc_refreshes_cli_presence_before_first_response(tmp_path):+def test_agent_supply_mutation_rpc_refreshes_cli_presence_before_writing(tmp_path):from core.handlers.model_hub.rpc import dispatch_model_hub_rpc- service, _store, _adapter = _service(tmp_path)+ service, store, _adapter = _service(tmp_path)calls = []- service.cli_presence_refresh = lambda: calls.append("refresh")+ service.cli_presence_refresh = lambda include_npm_global: calls.append(+ include_npm_global+ )service.cli_present_override = lambda backend: backend == "claude"payload = asyncio.run(dispatch_model_hub_rpc(service,- "get_agent_sources",- {"backend": "claude"},+ "set_agent_sources",+ {+ "backend": "claude",+ "sources": {+ "order": list(store.config.agents["claude"].sources.order),+ },+ },))assert payload["cli_present"] is True- assert calls == ["refresh"]+ assert calls == [True]+++def test_agent_supply_rpc_publishes_explicit_deep_discovery_after_fast_reads(+ tmp_path,+):+ from core.handlers.model_hub import rpc as model_hub_rpc++ service, _store, _adapter = _service(tmp_path)+ calls: list[bool] = []+ present = {"codex": False}+ deep_started = threading.Event()+ deep_release = threading.Event()++ def refresh(include_npm_global: bool) -> None:+ calls.append(include_npm_global)+ deep_started.set()+ deep_release.wait(timeout=2)+ present["codex"] = True++ service.cli_presence_refresh = refresh+ service.cli_present_override = lambda backend: present.get(backend, False)++ async def exercise() -> tuple[+ list[dict],+ list[dict],+ list[dict],+ list[dict],+ ]:+ first = await asyncio.wait_for(+ model_hub_rpc.dispatch_model_hub_rpc(service, "list_agents", {}),+ timeout=0.5,+ )+ assert calls == []++ refreshed = asyncio.create_task(+ model_hub_rpc.dispatch_model_hub_rpc(+ service,+ "list_agents",+ {"refresh_cli_presence": True},+ )+ )+ assert await asyncio.to_thread(deep_started.wait, 0.5)++ joined = asyncio.create_task(+ model_hub_rpc.dispatch_model_hub_rpc(+ service,+ "list_agents",+ {"refresh_cli_presence": True},+ )+ )+ second = await asyncio.wait_for(+ model_hub_rpc.dispatch_model_hub_rpc(service, "list_agents", {}),+ timeout=0.5,+ )+ deep_release.set()+ return first, second, await refreshed, await joined++ try:+ payloads = asyncio.run(exercise())+ finally:+ deep_release.set()++ first, second, refreshed, joined = payloads+ assert (+ next(agent for agent in first if agent["backend"] == "codex")["cli_present"]+ is False+ )+ assert (+ next(agent for agent in second if agent["backend"] == "codex")["cli_present"]+ is False+ )+ assert (+ next(agent for agent in refreshed if agent["backend"] == "codex")[+ "cli_present"+ ]+ is True+ )+ assert (+ next(agent for agent in joined if agent["backend"] == "codex")["cli_present"]+ is True+ )+ assert calls == [True]+++def test_agent_presence_refresh_crosses_the_controller_rpc_boundary(monkeypatch):+ from vibe import model_hub_client++ calls = []++ def rpc(operation, payload=None):+ calls.append((operation, payload))+ return []++ monkeypatch.setattr(model_hub_client, "_rpc_sync", rpc)++ agents = ModelHubRemoteService().list_agents(refresh_cli_presence=True)++ assert agents == []+ assert calls == [("list_agents", {"refresh_cli_presence": True})]+++def test_agents_route_requests_deep_presence_only_when_explicit(monkeypatch):+ calls = []++ class AgentService:+ def list_agents(self, *, refresh_cli_presence=False):+ calls.append(refresh_cli_presence)+ return []++ monkeypatch.setattr(ui_server, "_model_hub_service", AgentService)+ client = app.test_client()++ assert client.get("/api/models/agents").status_code == 200+ assert (+ client.get("/api/models/agents?refresh_cli_presence=1").status_code+ == 200+ )+ assert calls == [False, True]def test_usage_summary_rpc_reads_the_ledger_off_the_controller_loop(tmp_path):diff --git a/tests/test_ui_api.py b/tests/test_ui_api.pyindex 4038b3574..f5c9e4515 100644--- a/tests/test_ui_api.py+++ b/tests/test_ui_api.py@@ -1423,6 +1423,35 @@ def test_detect_cli_supports_explicit_path(monkeypatch, tmp_path):assert result["path"] == str(binary_path)+def test_resolve_cli_path_stops_before_npm_after_common_path_match(monkeypatch, tmp_path):+ codex_path = tmp_path / ".local" / "bin" / "codex"+ codex_path.parent.mkdir(parents=True)+ codex_path.write_text("#!/bin/sh\n")+ codex_path.chmod(0o755)++ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)+ monkeypatch.setattr(api.shutil, "which", lambda _binary: None)+ monkeypatch.setattr(+ api,+ "_npm_global_binary_candidates",+ lambda _binary: pytest.fail("npm discovery must not run after a direct match"),+ )++ assert api.resolve_cli_path("codex") == str(codex_path)+++def test_resolve_cli_path_fast_probe_never_queries_npm(monkeypatch, tmp_path):+ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)+ monkeypatch.setattr(api.shutil, "which", lambda _binary: None)+ monkeypatch.setattr(+ api,+ "_npm_global_binary_candidates",+ lambda _binary: pytest.fail("fast presence probes must not query npm"),+ )++ assert api.resolve_cli_path("missing-cli", include_npm_global=False) is None++@pytest.fixturedef only_tmp_binaries(monkeypatch, tmp_path):"""Make CLI discovery hermetic: only executables under ``tmp_path`` count as@@ -1557,6 +1586,129 @@ def test_detect_cli_finds_codex_in_npm_global_prefix(monkeypatch, tmp_path, onlyassert result["path"] == str(codex_path)+def test_resolve_cli_paths_queries_npm_prefix_once_for_a_backend_batch(+ monkeypatch,+ tmp_path,+ only_tmp_binaries,+):+ npm_path = tmp_path / "tools" / "npm"+ npm_path.parent.mkdir(parents=True, exist_ok=True)+ npm_path.write_text("#!/bin/sh\n")+ npm_path.chmod(0o755)+ inactive_npm = (+ tmp_path+ / ".nvm"+ / "versions"+ / "node"+ / "v18.20.0"+ / "bin"+ / "npm"+ )+ inactive_npm.parent.mkdir(parents=True, exist_ok=True)+ inactive_npm.write_text("#!/bin/sh\n")+ inactive_npm.chmod(0o755)++ prefix_path = tmp_path / ".npm-global"+ expected = {}+ for binary in ("claude", "codex", "opencode"):+ path = prefix_path / "bin" / binary+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("#!/bin/sh\n")+ path.chmod(0o755)+ expected[binary] = str(path)++ calls = []++ class CompletedProcess:+ returncode = 0+ stdout = f"{prefix_path}\n"+ stderr = ""++ def fake_run(cmd, **_kwargs):+ calls.append(cmd)+ return CompletedProcess()++ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)+ monkeypatch.setattr(+ api.shutil,+ "which",+ lambda binary: str(npm_path) if binary == "npm" else None,+ )+ monkeypatch.setattr(api.subprocess, "run", fake_run)++ assert api.resolve_cli_paths(list(expected)) == expected+ assert calls == [[str(npm_path), "config", "get", "prefix"]]+++def test_resolve_cli_paths_finds_backend_in_inactive_nvm_version_without_npm_query(+ monkeypatch,+ tmp_path,+ only_tmp_binaries,+):+ active_npm = (+ tmp_path+ / ".nvm"+ / "versions"+ / "node"+ / "v22.18.0"+ / "bin"+ / "npm"+ )+ active_npm.parent.mkdir(parents=True, exist_ok=True)+ active_npm.write_text("#!/bin/sh\n")+ active_npm.chmod(0o755)+ inactive_codex = (+ tmp_path+ / ".nvm"+ / "versions"+ / "node"+ / "v18.20.0"+ / "bin"+ / "codex"+ )+ inactive_codex.parent.mkdir(parents=True, exist_ok=True)+ inactive_codex.write_text("#!/bin/sh\n")+ inactive_codex.chmod(0o755)++ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)+ monkeypatch.setattr(+ api.shutil,+ "which",+ lambda binary: str(active_npm) if binary == "npm" else None,+ )+ monkeypatch.setattr(+ api.subprocess,+ "run",+ lambda *_args, **_kwargs: pytest.fail(+ "an NVM bin match must not require npm prefix discovery"+ ),+ )++ assert api.resolve_cli_paths(["codex"]) == {"codex": str(inactive_codex)}+++def test_resolve_cli_paths_preserves_completed_paths_when_other_probes_fail(+ monkeypatch,+):+ def resolve(binary, *, include_npm_global):+ assert include_npm_global is False+ if binary == "codex":+ raise OSError("NVM inventory changed during discovery")+ return f"/resolved/{binary}" if binary == "claude" else None++ def fail_prefix_probe():+ raise OSError("npm disappeared")++ monkeypatch.setattr(api, "resolve_cli_path", resolve)+ monkeypatch.setattr(api, "_npm_global_prefixes", fail_prefix_probe)++ assert api.resolve_cli_paths(["claude", "codex", "opencode"]) == {+ "claude": "/resolved/claude",+ "codex": None,+ "opencode": None,+ }++def test_install_agent_returns_resolved_path(monkeypatch):class CompletedProcess:returncode = 0diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxindex c00a6d4e6..bdfbf72a3 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -4,7 +4,7 @@ import { join } from 'node:path';import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { I18nextProvider } from 'react-i18next';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { ToastProvider } from '@/context/ToastProvider';import i18n from '@/i18n';@@ -131,6 +131,10 @@ const renderPage = (sources: Source[]) => {);};+beforeEach(() => {+ vi.spyOn(modelsApi, 'refreshAgentPresence').mockReturnValue(new Promise(() => {}));+});+afterEach(() => {cleanup();vi.restoreAllMocks();@@ -220,6 +224,78 @@ describe('SettingsModelsPage surface branches', () => {expect(screen.queryByText(/backends are direct|个后端均为直连/i)).toBeNull();});+ it('publishes a newly discovered backend into the already-open page', async () => {+ const unavailable = [+ { ...directAgent('claude'), cli_present: false },+ { ...directAgent('codex'), cli_present: false },+ { ...directAgent('opencode'), cli_present: false },+ ];+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);+ const available = [+ unavailable[0],+ directAgent('codex'),+ unavailable[2],+ ];+ vi.spyOn(modelsApi, 'listAgents')+ .mockResolvedValueOnce(unavailable)+ .mockResolvedValue(available);+ vi.mocked(modelsApi.refreshAgentPresence).mockResolvedValue(available);+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);++ render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <SettingsModelsPage />+ </I18nextProvider>+ </ToastProvider>,+ );++ expect(await screen.findByRole('button', { name: /^Switch to Gateway$|^切换到网关$/i })).toBeTruthy();+ expect(screen.queryByText(/No agent backend was found|没有找到 Agent 后端/i)).toBeNull();+ expect(modelsApi.refreshAgentPresence).toHaveBeenCalledOnce();+ });++ it('retries deep backend detection without remounting the page', async () => {+ const unavailable = [+ { ...directAgent('claude'), cli_present: false },+ { ...directAgent('codex'), cli_present: false },+ { ...directAgent('opencode'), cli_present: false },+ ];+ const available = [+ unavailable[0],+ directAgent('codex'),+ unavailable[2],+ ];+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);+ vi.spyOn(modelsApi, 'listAgents')+ .mockResolvedValueOnce(unavailable)+ .mockResolvedValueOnce(unavailable)+ .mockResolvedValue(available);+ vi.mocked(modelsApi.refreshAgentPresence)+ .mockResolvedValueOnce(unavailable)+ .mockResolvedValueOnce(available);+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);++ render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <SettingsModelsPage />+ </I18nextProvider>+ </ToastProvider>,+ );++ expect(await screen.findByText(/No agent backend was found|没有找到 Agent 后端/i)).toBeTruthy();+ const retry = await screen.findByRole('button', { name: /Detect Agent backends again|重新检测 Agent 后端/i });+ await waitFor(() => expect((retry as HTMLButtonElement).disabled).toBe(false));+ const user = userEvent.setup();+ await user.click(retry);++ expect(await screen.findByRole('button', { name: /^Switch to Gateway$|^切换到网关$/i })).toBeTruthy();+ expect(modelsApi.refreshAgentPresence).toHaveBeenCalledTimes(2);+ });+it('keeps an unread runtime visible on the direct-only surface', async () => {vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex 4f1f81087..0b30dbd51 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -1,5 +1,5 @@import * as React from 'react';-import { ArrowLeft, Gauge, LoaderCircle, Power, Route, ScrollText } from 'lucide-react';+import { ArrowLeft, Gauge, LoaderCircle, Power, RefreshCw, Route, ScrollText } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Badge } from '@/components/ui/badge';@@ -399,6 +399,7 @@ export const SettingsModelsPage: React.FC = () => {const [sourceIntentAuthority] = React.useState(createIntentAuthority);const [sourceCollectionReads] = React.useState(() => createSourceCollectionReadAuthority(modelsApi));const [agentCollectionReads] = React.useState(() => createAgentCollectionReadAuthority(modelsApi));+ const [presenceRefreshing, setPresenceRefreshing] = React.useState(false);const sourceMutationReport = useSourceMutationReport();const overviewRef = React.useRef<HTMLDivElement>(null);const pageRef = React.useRef<HTMLDivElement>(null);@@ -729,9 +730,27 @@ export const SettingsModelsPage: React.FC = () => {return result;}, [refresh, sourceCollectionReads, sourceEntityAuthority, sourceWriteRegistry]);+ const refreshAgentPresence = React.useCallback(async () => {+ setPresenceRefreshing(true);+ try {+ const result = await agentCollectionReads.refresh();+ if (!aliveRef.current || result.kind === 'stale') return;+ setSupplyRead(readyRegion(result.value));+ } finally {+ if (aliveRef.current) setPresenceRefreshing(false);+ }+ }, [agentCollectionReads]);+React.useEffect(() => {- void refresh();- }, [refresh]);+ let current = true;+ void refresh().then(() => {+ if (!current) return;+ void refreshAgentPresence().catch(() => {+ // The fast snapshot remains authoritative if optional deep discovery fails.+ });+ });+ return () => { current = false; };+ }, [refresh, refreshAgentPresence]);const retrySources = React.useCallback(async () => {setSourcesRead(beginRegionRead);@@ -739,9 +758,13 @@ export const SettingsModelsPage: React.FC = () => {}, [refresh]);const retrySupply = React.useCallback(async () => {- setSupplyRead(beginRegionRead);- await refresh();- }, [refresh]);+ if (presenceRefreshing) return;+ try {+ await refreshAgentPresence();+ } catch {+ if (aliveRef.current) setSupplyRead(failRegionRead);+ }+ }, [presenceRefreshing, refreshAgentPresence]);const retryEvents = React.useCallback(async () => {await refreshEventHead();@@ -1152,6 +1175,16 @@ export const SettingsModelsPage: React.FC = () => {directCount={directEmpty ? installedAgents.length : undefined}/>{runtimeConfigurationVisible && !directEmpty && <TakeoverPill count={takeoverCount} />}+ {runtimeConfigurationVisible && <Button+ type="button"+ variant="ghost"+ size="icon"+ className="size-8"+ disabled={presenceRefreshing}+ aria-label={t('settings.models.direct.action.refreshAgents')}+ title={t('settings.models.direct.action.refreshAgents')}+ onClick={() => void retrySupply()}+ ><RefreshCw aria-hidden className={cn('size-3.5', presenceRefreshing && 'animate-spin')} /></Button>}<span title={runtimeSwitchLabel}><ToggleSwitchenabled={runtimeEnabled}diff --git a/ui/src/components/settings/models/asyncLifetime.test.ts b/ui/src/components/settings/models/asyncLifetime.test.tsindex 1136fd62c..edae5e8f0 100644--- a/ui/src/components/settings/models/asyncLifetime.test.ts+++ b/ui/src/components/settings/models/asyncLifetime.test.ts@@ -334,7 +334,7 @@ describe('Source entity landing through the shared authority', () => {expect(page).not.toMatch(/const sourceMutation\s*=|activeSourceGenerations/);expect(page).toMatch(/await refreshAuthority\.run/);expect(sourceRetry).toMatch(/await refresh\(\)/);- expect(supplyRetry).toMatch(/await refresh\(\)/);+ expect(supplyRetry).toMatch(/await refreshAgentPresence\(\)/);expect(sourceRetry).not.toMatch(/modelsApi\.listSources/);expect(supplyRetry).not.toMatch(/modelsApi\.listAgents/);});diff --git a/ui/src/components/settings/models/collectionReadAuthority.test.ts b/ui/src/components/settings/models/collectionReadAuthority.test.tsindex 6e80d59c9..89aa7a75f 100644--- a/ui/src/components/settings/models/collectionReadAuthority.test.ts+++ b/ui/src/components/settings/models/collectionReadAuthority.test.ts@@ -46,11 +46,30 @@ describe('collection read authority', () => {await expect(first).resolves.toEqual({ kind: 'stale' });});+ it('publishes deep CLI discovery after a concurrent fast read', async () => {+ const refresh = deferred<AgentSupply[]>();+ const api = {+ listAgents: vi.fn()+ .mockResolvedValueOnce([agent('direct')])+ .mockResolvedValueOnce([agent('hub')]),+ refreshAgentPresence: vi.fn().mockReturnValue(refresh.promise),+ };+ const authority = createAgentCollectionReadAuthority(api);++ const pending = authority.refresh();+ await expect(authority.read()).resolves.toEqual({ kind: 'current', value: [agent('direct')] });+ refresh.resolve([agent('hub')]);++ await expect(pending).resolves.toEqual({ kind: 'current', value: [agent('hub')] });+ expect(api.refreshAgentPresence).toHaveBeenCalledOnce();+ expect(api.listAgents).toHaveBeenCalledTimes(2);+ });+it('keeps collection endpoints private to the generation authority', () => {const allowed = new Set(['collectionReadAuthority.ts', 'modelsApi.ts']);const violations = productFiles(__dirname).flatMap((path) => {if (allowed.has(path.split('/').at(-1) ?? '')) return [];- return /\.list(?:Agents|Sources)\s*\(/.test(readFileSync(path, 'utf8')) ? [path] : [];+ return /\.(?:list(?:Agents|Sources)|refreshAgentPresence)\s*\(/.test(readFileSync(path, 'utf8')) ? [path] : [];});expect(violations).toEqual([]);diff --git a/ui/src/components/settings/models/collectionReadAuthority.ts b/ui/src/components/settings/models/collectionReadAuthority.tsindex e3fbbed46..d1657d86b 100644--- a/ui/src/components/settings/models/collectionReadAuthority.ts+++ b/ui/src/components/settings/models/collectionReadAuthority.ts@@ -7,6 +7,7 @@ export type CollectionReadResult<T> =export type CollectionReadAuthority<T> = {read: () => Promise<CollectionReadResult<T>>;+ refresh: () => Promise<CollectionReadResult<T>>;readValue: () => Promise<T>;invalidate: () => void;};@@ -20,21 +21,32 @@ class SupersededCollectionRead extends Error {/** The only owner allowed to call a collection endpoint. Every read carries a* generation, including reconciliation reads that do not directly render. */-const createCollectionReadAuthority = <T>(readCollection: () => Promise<T>): CollectionReadAuthority<T> => {+const createCollectionReadAuthority = <T>(+ readCollection: () => Promise<T>,+ refreshCollection?: () => Promise<unknown>,+): CollectionReadAuthority<T> => {let generation = 0;- const read = async (): Promise<CollectionReadResult<T>> => {+ const readFrom = async (reader: () => Promise<T>): Promise<CollectionReadResult<T>> => {const mine = ++generation;try {- const value = await readCollection();+ const value = await reader();return mine === generation ? { kind: 'current', value } : { kind: 'stale' };} catch (error) {if (mine !== generation) return { kind: 'stale' };throw error;}};+ const read = () => readFrom(readCollection);+ const refresh = refreshCollection+ ? async () => {+ await refreshCollection();+ return read();+ }+ : read;return {read,+ refresh,readValue: async () => {const result = await read();if (result.kind === 'stale') throw new SupersededCollectionRead();@@ -49,5 +61,11 @@ export const createSourceCollectionReadAuthority = (): CollectionReadAuthority<Source[]> => createCollectionReadAuthority(() => api.listSources());export const createAgentCollectionReadAuthority = (- api: Pick<ModelsApi, 'listAgents'> = modelsApi,-): CollectionReadAuthority<AgentSupply[]> => createCollectionReadAuthority(() => api.listAgents());+ api: Pick<ModelsApi, 'listAgents'> & Partial<Pick<ModelsApi, 'refreshAgentPresence'>> = modelsApi,+): CollectionReadAuthority<AgentSupply[]> => {+ const refreshPresence = api.refreshAgentPresence;+ return createCollectionReadAuthority(+ () => api.listAgents(),+ refreshPresence ? () => refreshPresence() : undefined,+ );+};diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex 7a147e768..2a976a92b 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -110,6 +110,8 @@ export type ModelsApi = {* status/submit response as `OAuthResult.repaired`. */reauthSource(id: string): Promise<OAuthFlow>;listAgents(): Promise<AgentSupply[]>;+ /** Deep CLI discovery used after the fast Agent snapshot has painted. */+ refreshAgentPresence(): Promise<AgentSupply[]>;/** Per-backend enabled subset + order (the 来源顺序 drawer's read). */getAgentSources(backend: AgentBackend): Promise<AgentSupply>;/** Total write of the exact stored source order. */@@ -448,6 +450,7 @@ export const modelsApi: ModelsApi = {// supply consent: guarded inventory mutations separately echo the server plan.reauthSource: (id) => call<{ flow?: OAuthFlow } & OAuthFlow>(`/api/models/sources/${encodeURIComponent(id)}/reauth`, jsonInit('POST', { acknowledge_irreversible: true })).then((r) => (r.flow ?? r) as OAuthFlow),listAgents: () => call<{ agents: AgentSupply[] }>('/api/models/agents').then((r) => r.agents),+ refreshAgentPresence: () => call<{ agents: AgentSupply[] }>('/api/models/agents?refresh_cli_presence=1').then((r) => r.agents),getAgentSources: (backend) => call<{ agent: AgentSupply }>(`/api/models/agents/${backend}/sources`).then((r) => r.agent),// The body is TOTAL and closed: the route rejects unknown keys, so// `contract_version` is deliberately absent (unlike every other write here).diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 337d8f6e4..3f04e1e4c 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -804,7 +804,8 @@}},"action": {- "switchToGateway": "Switch to gateway"+ "switchToGateway": "Switch to gateway",+ "refreshAgents": "Detect Agent backends again"},"benefits": {"title": "Switch to the gateway and you gain three things",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 418ae6703..842807538 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -804,7 +804,8 @@}},"action": {- "switchToGateway": "切换到网关"+ "switchToGateway": "切换到网关",+ "refreshAgents": "重新检测 Agent 后端"},"benefits": {"title": "切换到网关,你会多出三件事",diff --git a/vibe/api.py b/vibe/api.pyindex 7ee2d54f4..e2ccd825d 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -237,23 +237,8 @@ def _npm_global_binary_candidates(binary: str) -> list[Path]:if not binary or binary == "npm":return []- npm_paths: list[Path] = []- for candidate in _candidate_cli_paths("npm"):- if _is_executable_file(candidate) and candidate not in npm_paths:- npm_paths.append(candidate)-- which_npm = shutil.which("npm")- if which_npm:- npm_candidate = Path(which_npm)- if npm_candidate not in npm_paths:- npm_paths.append(npm_candidate)-candidates: list[Path] = []- for npm_path in npm_paths:- prefix_path = _npm_prefix_for(npm_path)- if prefix_path is None:- continue-+ for prefix_path in _npm_global_prefixes():for candidate in _npm_binary_candidates_for_prefix(prefix_path, binary):if candidate not in candidates:candidates.append(candidate)@@ -261,6 +246,28 @@ def _npm_global_binary_candidates(binary: str) -> list[Path]:return candidates+def _npm_global_prefixes() -> list[Path]:+ # Global packages belong to the npm selected by the current environment.+ # Querying every historical NVM installation makes one missing CLI cost up+ # to five seconds per Node version without improving that answer.+ which_npm = shutil.which("npm")+ npm_path = Path(which_npm) if which_npm else next(+ (+ candidate+ for candidate in _candidate_cli_paths(+ "npm",+ include_npm_global=False,+ )+ if _is_executable_file(candidate)+ ),+ None,+ )+ if npm_path is None:+ return []+ prefix_path = _npm_prefix_for(npm_path)+ return [prefix_path] if prefix_path is not None else []++def _npm_prefix_for(npm_path: str | Path) -> Path | None:try:result = subprocess.run(@@ -314,7 +321,11 @@ def _windows_executable_candidates(candidates: list[Path]) -> list[Path]:return result-def _candidate_cli_paths(binary: str) -> list[Path]:+def _candidate_cli_paths(+ binary: str,+ *,+ include_npm_global: bool = True,+) -> list[Path]:if not binary:return []@@ -343,15 +354,23 @@ def _candidate_cli_paths(binary: str) -> list[Path]:]if os.name == "nt":common_candidates = _windows_executable_candidates(common_candidates)- for candidate in common_candidates + _nvm_binary_candidates(binary) + _npm_global_binary_candidates(binary):+ for candidate in common_candidates + _nvm_binary_candidates(binary):if candidate not in candidates:candidates.append(candidate)+ if include_npm_global:+ for candidate in _npm_global_binary_candidates(binary):+ if candidate not in candidates:+ candidates.append(candidate)return candidates-def resolve_cli_path(binary: str) -> str | None:- for candidate in _candidate_cli_paths(binary):+def _resolve_cli_path_once(+ binary: str,+ *,+ include_npm_global: bool,+) -> str | None:+ for candidate in _candidate_cli_paths(binary, include_npm_global=False):if _is_executable_file(candidate):return str(candidate)@@ -359,6 +378,25 @@ def resolve_cli_path(binary: str) -> str | 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+++def resolve_cli_path(+ binary: str,+ *,+ include_npm_global: bool = True,+) -> str | None:+ path = _resolve_cli_path_once(+ binary,+ include_npm_global=include_npm_global,+ )+ if path:+ return path+# The stored cli_path was an absolute path that no longer exists. Most# common cause: an upstream installer moved the binary out from under us.# Real-world example: Claude Code's official ``install.sh`` puts the@@ -380,17 +418,77 @@ def resolve_cli_path(binary: str) -> str | None:if expanded.is_absolute() or has_path_separator:basename = expanded.nameif basename and basename != binary:- for candidate in _candidate_cli_paths(basename):- if _is_executable_file(candidate):- logger.info(- "resolve_cli_path: stored path %s missing; falling back to %s",- binary,- candidate,- )- return str(candidate)+ fallback = _resolve_cli_path_once(+ basename,+ include_npm_global=include_npm_global,+ )+ if fallback:+ logger.info(+ "resolve_cli_path: stored path %s missing; falling back to %s",+ binary,+ fallback,+ )+ return fallbackreturn None+def resolve_cli_paths(+ binaries: list[str],+ *,+ include_npm_global: bool = True,+) -> dict[str, str | None]:+ """Resolve a CLI batch while querying each npm installation only once."""++ resolved: dict[str, str | None] = {}+ for binary in binaries:+ try:+ resolved[binary] = resolve_cli_path(+ binary,+ include_npm_global=False,+ )+ except Exception:+ logger.warning("CLI path probe failed for %s", binary, exc_info=True)+ resolved[binary] = None+ if not include_npm_global or all(path is not None for path in resolved.values()):+ return resolved++ try:+ prefixes = _npm_global_prefixes()+ except Exception:+ logger.warning("npm global prefix probe failed", exc_info=True)+ return resolved+ for binary, path in resolved.items():+ if path is not None or not binary:+ continue+ expanded = Path(os.path.expanduser(binary))+ has_path_separator = os.sep in binary or (+ os.altsep is not None and os.altsep in binary+ )+ lookup_name = (+ expanded.name if expanded.is_absolute() or has_path_separator else binary+ )+ for prefix in prefixes:+ npm_path = next(+ (+ str(candidate)+ for candidate in _npm_binary_candidates_for_prefix(prefix, lookup_name)+ if _is_executable_file(candidate)+ ),+ None,+ )+ if npm_path is None:+ continue+ resolved[binary] = npm_path+ if lookup_name != binary:+ logger.info(+ "resolve_cli_paths: stored path %s missing; falling back to %s",+ binary,+ npm_path,+ )+ break+ return resolved++def _command_env_for(binary_path: str | None) -> dict[str, str]:env = {**os.environ, "PATH": os.environ.get("PATH", "")}if not binary_path:diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.pyindex 6eee2e8a4..0141aa1dc 100644--- a/vibe/model_hub_client.py+++ b/vibe/model_hub_client.py@@ -140,8 +140,11 @@ class ModelHubRemoteService:},)- def list_agents(self) -> list[dict]:- return _rpc_sync("list_agents")+ def list_agents(self, *, refresh_cli_presence: bool = False) -> list[dict]:+ return _rpc_sync(+ "list_agents",+ {"refresh_cli_presence": True} if refresh_cli_presence else None,+ )def get_agent_sources(self, backend: str) -> dict:return _rpc_sync("get_agent_sources", {"backend": backend})diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex f06b7e8e9..68dcdfced 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -4557,7 +4557,15 @@ def model_hub_agents_get():from core.handlers.model_hub import ModelHubErrortry:- return _model_hub_success(agents=_model_hub_service().list_agents())+ service = _model_hub_service()+ refresh_cli_presence = request.args.get("refresh_cli_presence") == "1"+ return _model_hub_success(+ agents=(+ service.list_agents(refresh_cli_presence=True)+ if refresh_cli_presence+ else service.list_agents()+ )+ )except ModelHubError as exc:return _model_hub_error(exc)