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(auth): use configured Claude CLI for web OAuth (#2268)

Max3a001ad70baf
diff --git a/config/v2_compat.py b/config/v2_compat.py
index d5432950e..679f18024 100644
--- a/config/v2_compat.py
+++ b/config/v2_compat.py
@@ -101,7 +101,7 @@ class AppCompatConfig:
return [self.platform]
-def _runtime_agent_cli_path(
+def runtime_agent_cli_path(
configured: str | None,
default: str,
*,
@@ -109,7 +109,8 @@ def _runtime_agent_cli_path(
) -> str:
"""Project one saved selector to the executable used by desktop Runtime."""
- selected = str(configured or default)
+ selected = str(configured).strip() if configured is not None else default
+ selected = selected or default
from vibe.upgrade import is_desktop_managed_runtime
if not resolve_agent_paths or not is_desktop_managed_runtime():
@@ -140,7 +141,7 @@ def to_app_config(
permission_mode="bypassPermissions",
cwd=v2.runtime.default_cwd,
system_prompt=None,
- cli_path=_runtime_agent_cli_path(
+ cli_path=runtime_agent_cli_path(
v2.agents.claude.cli_path,
"claude",
resolve_agent_paths=resolve_agent_paths,
@@ -159,7 +160,7 @@ def to_app_config(
if v2.agents.codex.enabled:
codex = CodexCompatConfig(
enabled=True,
- binary=_runtime_agent_cli_path(
+ binary=runtime_agent_cli_path(
v2.agents.codex.cli_path,
"codex",
resolve_agent_paths=resolve_agent_paths,
@@ -172,7 +173,7 @@ def to_app_config(
if v2.agents.opencode.enabled:
opencode = OpenCodeCompatConfig(
enabled=True,
- binary=_runtime_agent_cli_path(
+ binary=runtime_agent_cli_path(
v2.agents.opencode.cli_path,
"opencode",
resolve_agent_paths=resolve_agent_paths,
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 96a708f9e..8a46440ad 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -679,7 +679,15 @@ class AgentAuthService:
# binary``. Without these fallbacks, setup / logout / test
# flows ignore a non-default cli_path and fall through to
# ``$PATH``, breaking installs that pin a specific binary.
- backend_cfg = self._resolve_backend_config(backend)
+ config = getattr(getattr(self, "controller", None), "config", None)
+ # Live IM controllers hand ``AppCompatConfig``, whose top-level
+ # selector is already the runtime projection. Anything read from the
+ # V2 ``agents`` shape (the Web stub controller, or a reload below) is a
+ # raw persisted selector and is projected the same way before use.
+ backend_cfg = getattr(config, backend, None) if config is not None else None
+ runtime_projected = backend_cfg is not None
+ if backend_cfg is None:
+ backend_cfg = self._resolve_backend_config(backend)
# Compatibility projection can erase recovery provenance, so inventory
# validates persisted evidence even when a live backend object exists.
if strict or backend_cfg is None:
@@ -706,7 +714,18 @@ class AgentAuthService:
exc_info=True,
)
cli_path = getattr(backend_cfg, "cli_path", None) or getattr(backend_cfg, "binary", None)
- return cli_path or backend
+ if runtime_projected:
+ return cli_path or backend
+ from config.v2_compat import runtime_agent_cli_path
+
+ if backend == "claude":
+ # Normalize the raw V2 selector before desktop resolution. A
+ # copied ``" claude "`` must resolve as the default executable,
+ # rather than as a literal filename that the resolver cannot find.
+ from vibe.claude_config import normalize_claude_cli_path
+
+ cli_path = normalize_claude_cli_path(cli_path)
+ return runtime_agent_cli_path(cli_path, backend, resolve_agent_paths=True)
def _resolve_backend_probe_cwd(self, backend: str, *, prepare: bool = False) -> str:
"""Resolve the configured runtime cwd without mutating it by default."""
@@ -1559,6 +1578,7 @@ class AgentAuthService:
CLAUDE_MEMORY_DISABLED_SETTINGS,
CLAUDE_SETTING_SOURCES,
build_claude_subprocess_env,
+ normalize_claude_cli_path,
)
# ``force_oauth=True`` because this code path IS the OAuth
@@ -1591,6 +1611,12 @@ class AgentAuthService:
get_cli_override = getattr(session_handler, "_get_claude_cli_path_override", None)
cli_override = get_cli_override() if callable(get_cli_override) else None
+ if not cli_override:
+ # Web-initiated flows use the web controller stub, which has no
+ # session handler. Fall back to the configured backend binary so
+ # OAuth uses the same Claude Code version as normal Agent turns
+ # instead of silently selecting the SDK's bundled CLI.
+ cli_override = normalize_claude_cli_path(self._get_cli_binary("claude"))
if cli_override:
option_kwargs["cli_path"] = cli_override
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index a694b580b..ee68b6c43 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -1071,18 +1071,9 @@ class SessionHandler(BaseHandler):
return disallowed
def _get_claude_cli_path_override(self) -> Optional[str]:
- cli_path = getattr(getattr(self.config, "claude", None), "cli_path", None)
- if cli_path is None:
- return None
-
- normalized = str(cli_path).strip()
- if not normalized:
- return None
-
- if normalized == "claude":
- return None
+ from vibe.claude_config import normalize_claude_cli_path
- return os.path.expanduser(normalized)
+ return normalize_claude_cli_path(getattr(getattr(self.config, "claude", None), "cli_path", None))
def _load_agent_file(self, agent_name: str, working_path: str) -> Optional[Dict[str, Any]]:
"""Load an agent file and return its parsed content.
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index e4d207413..e73ccd819 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -351,6 +351,15 @@ scenarios:
supporting_tests:
- tests/test_native_writer_custody.py::test_hub_backend_admits_creating_the_empty_native_subscription_slot
- tests/test_model_hub_api.py::test_native_oauth_custody_refusal_is_not_reported_as_engine_down
+ - id: AUTH-SETUP-911
+ name: Web Claude OAuth launches the same CLI as normal Agent turns for padded paths and the desktop default selector
+ status: covered
+ kind: historical_regression
+ layer: scenario
+ backend: claude
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_web_claude_oauth_launches_the_persisted_cli_path
+ supporting_tests:
+ - tests/test_claude_cli_path.py::test_web_auth_uses_configured_claude_cli_path_without_session_handler
- id: AUTH-SETUP-119
name: Runtime manual provider code reaches native persistence and controller-confirmed readiness
status: covered
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index 0ff20be8a..ec825622b 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -961,6 +961,100 @@ def test_remote_web_oauth_cold_launch_retry_is_single_owner(monkeypatch, tmp_pat
)
+ "selector_case",
+ ["padded_path", "desktop_default", "desktop_padded_default"],
+)
+def test_web_claude_oauth_launches_the_persisted_cli_path(monkeypatch, tmp_path, selector_case):
+ """Scenario: AUTH-SETUP-911"""
+ import core.agent_auth_service as auth_module
+ from vibe import api as vibe_api
+
+ claude_home = tmp_path / "claude-home"
+ claude_home.mkdir()
+ if selector_case == "padded_path":
+ # A path pasted into Settings keeps its surrounding whitespace on disk.
+ configured_cli = tmp_path / "bin" / "claude-new"
+ persisted_selector = f" {configured_cli} "
+ else:
+ # A GUI-launched desktop Runtime has no shell PATH; normal Agent turns
+ # resolve the default selector to the user's installed executable.
+ configured_cli = tmp_path / ".local" / "bin" / "claude"
+ configured_cli.parent.mkdir(parents=True)
+ configured_cli.write_text("#!/bin/sh\n", encoding="utf-8")
+ configured_cli.chmod(0o755)
+ persisted_selector = " claude " if selector_case == "desktop_padded_default" else "claude"
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")
+ monkeypatch.setenv("PATH", "")
+ monkeypatch.setattr("vibe.cli_paths.Path.home", lambda: tmp_path)
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(claude_home))
+ monkeypatch.setattr(auth_module, "CLAUDE_SDK_AVAILABLE", True)
+
+ harness = SimpleNamespace(launches=[], control_requests=[], disconnects=0)
+
+ class FakeClaudeSDKClient:
+ def __init__(self, *, options):
+ harness.launches.append(options)
+ self._query = SimpleNamespace(_send_control_request=self._send_control_request)
+
+ async def connect(self):
+ return None
+
+ async def _send_control_request(self, request, *, timeout):
+ harness.control_requests.append(request["subtype"])
+ if request["subtype"] == "claude_authenticate":
+ return {"manualUrl": "https://claude.invalid/authorize"}
+ # The login stays pending until the user cancels it.
+ await asyncio.Event().wait()
+
+ async def disconnect(self):
+ harness.disconnects += 1
+
+ # The Web surface builds its own service over the stub controller, which
+ # re-reads persisted config and has no IM session handler.
+ service = AgentAuthService(vibe_api._WebControllerStub())
+ monkeypatch.setattr(vibe_api, "_get_oauth_service", lambda: service)
+ monkeypatch.setattr(auth_module, "ClaudeSDKClient", FakeClaudeSDKClient)
+ runner = ScenarioRunner(harness)
+
+ def save_cli_selector(current):
+ config = V2Config(
+ mode="self_host",
+ version="v2",
+ slack=SlackConfig(bot_token=""),
+ runtime=RuntimeConfig(default_cwd=str(tmp_path)),
+ agents=AgentsConfig(),
+ )
+ config.agents.claude.cli_path = persisted_selector
+ save_direct_auth_config(config)
+
+ async def start_web_oauth(current):
+ current.start = await vibe_api.start_oauth_web_async("claude", force_reset=False)
+
+ async def cancel_web_oauth(current):
+ current.cancel = await vibe_api.cancel_oauth_web_async(current.start["flow_id"])
+
+ asyncio.run(
+ runner.run(
+ ScenarioStep("save_cli_selector", save_cli_selector),
+ ScenarioStep("start_web_oauth", start_web_oauth),
+ ScenarioStep("cancel_web_oauth", cancel_web_oauth),
+ )
+ )
+
+ assert harness.start["ok"] is True
+ assert harness.start["state"] == "awaiting_code"
+ assert harness.start["url"] == "https://claude.invalid/authorize"
+ assert [options.cli_path for options in harness.launches] == [str(configured_cli)]
+ assert harness.control_requests[0] == "claude_authenticate"
+ assert harness.cancel["ok"] is True
+ assert harness.disconnects == 1
+ ScenarioExpect.step_history(
+ runner,
+ ["save_cli_selector", "start_web_oauth", "cancel_web_oauth"],
+ )
+
+
def _save_remote_session_authorization_config(instance_kind: str) -> V2Config:
config = _save_remote_web_auth_config()
cloud = config.remote_access.vibe_cloud
diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.py
index 0e823594f..66afe4051 100644
--- a/tests/test_claude_cli_path.py
+++ b/tests/test_claude_cli_path.py
@@ -14,6 +14,7 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import core.agent_auth_service as agent_auth_service_module
import core.handlers.session_handler as session_handler_module
from config.v2_compat import to_app_config
from config.v2_config import (
@@ -27,6 +28,7 @@ from config.v2_config import (
)
from config.v2_settings import RoutingSettings
from core import git_runtime as git_runtime_module
+from core.agent_auth_service import AgentAuthService
from core.handlers.session_handler import SessionHandler
from core.runtime_activation import RuntimeActivationRegistry
from core.runtime_ownership import RuntimeTargetOwnershipSnapshot, SessionRuntimeDisposition
@@ -164,6 +166,60 @@ def test_to_app_config_preserves_claude_cli_path() -> None:
assert compat.claude.cli_path == "/usr/local/bin/claude-proxy"
+ ("configured_cli", "expected_cli"),
+ [
+ ("/usr/local/bin/claude-new", "/usr/local/bin/claude-new"),
+ (" /usr/local/bin/claude-new ", "/usr/local/bin/claude-new"),
+ (" claude ", None),
+ ],
+)
+async def test_web_auth_uses_configured_claude_cli_path_without_session_handler(
+ monkeypatch,
+ configured_cli: str,
+ expected_cli: str | None,
+) -> None:
+ captured: dict[str, Any] = {}
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ captured["options"] = options
+
+ async def connect(self) -> None:
+ captured["connected"] = True
+
+ class _Governor:
+ @staticmethod
+ def apply_to_pid(_pid, label="agent"):
+ captured["governor_label"] = label
+
+ monkeypatch.setattr(agent_auth_service_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(agent_auth_service_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+ monkeypatch.setattr(agent_auth_service_module, "get_claude_client_pid", lambda _client: None)
+ monkeypatch.setattr(agent_auth_service_module, "governor_from_controller", lambda _controller: _Governor())
+
+ controller = SimpleNamespace(
+ config=SimpleNamespace(
+ agents=SimpleNamespace(
+ claude=SimpleNamespace(
+ cli_path=configured_cli,
+ auth_mode="oauth",
+ api_key=None,
+ base_url=None,
+ )
+ )
+ )
+ )
+ service = object.__new__(AgentAuthService)
+ service.controller = controller
+
+ await service._create_claude_control_client()
+
+ assert captured["connected"] is True
+ assert captured["options"].cli_path == expected_cli
+
+
def test_to_app_config_resolves_all_desktop_backend_executables(monkeypatch, tmp_path: Path) -> None:
binaries = {
"claude": tmp_path / ".local" / "bin" / "claude",
@@ -184,7 +240,7 @@ def test_to_app_config_resolves_all_desktop_backend_executables(monkeypatch, tmp
slack=SlackConfig(),
runtime=RuntimeConfig(default_cwd="/tmp/workdir"),
agents=AgentsConfig(
- claude=ClaudeConfig(cli_path="claude"),
+ claude=ClaudeConfig(cli_path=" claude "),
codex=CodexConfig(cli_path="codex"),
opencode=OpenCodeConfig(cli_path="opencode"),
),
@@ -199,6 +255,31 @@ def test_to_app_config_resolves_all_desktop_backend_executables(monkeypatch, tmp
assert compat.opencode.binary == str(binaries["opencode"])
+def test_auth_service_projects_only_raw_backend_selectors(monkeypatch, tmp_path: Path) -> None:
+ installed = tmp_path / ".local" / "bin" / "claude"
+ installed.parent.mkdir(parents=True)
+ installed.write_text("#!/bin/sh\n", encoding="utf-8")
+ installed.chmod(0o755)
+ monkeypatch.setenv("AVIBE_DESKTOP_MANAGED_RUNTIME", "1")
+ monkeypatch.setenv("PATH", "")
+ monkeypatch.setattr("vibe.cli_paths.Path.home", lambda: tmp_path)
+
+ web_service = object.__new__(AgentAuthService)
+ web_service.controller = SimpleNamespace(
+ config=SimpleNamespace(agents=SimpleNamespace(claude=SimpleNamespace(cli_path="claude")))
+ )
+ live_service = object.__new__(AgentAuthService)
+ live_service.controller = SimpleNamespace(config=SimpleNamespace(claude=SimpleNamespace(cli_path="claude")))
+
+ # The Web stub reads raw V2 selectors and projects them like to_app_config.
+ assert web_service._get_cli_binary("claude") == str(installed)
+ # A live controller's AppCompatConfig is already projected; keep it as-is.
+ assert live_service._get_cli_binary("claude") == "claude"
+
+ web_service.controller.config.agents.claude.cli_path = " claude "
+ assert web_service._get_cli_binary("claude") == str(installed)
+
+
def test_to_app_config_keeps_missing_private_backend_selectors_off_path(monkeypatch, tmp_path: Path) -> None:
from vibe.cli_paths import resolve_cli_path
diff --git a/vibe/claude_config.py b/vibe/claude_config.py
index 0eb5006ed..b2f7ce7aa 100644
--- a/vibe/claude_config.py
+++ b/vibe/claude_config.py
@@ -423,6 +423,21 @@ def read_claude_credential_from_settings(
return None, None
+def normalize_claude_cli_path(cli_path: Any) -> Optional[str]:
+ """Return the configured Claude CLI to launch, or ``None`` for the SDK default.
+
+ Every Claude SDK launch site shares this so one saved ``cli_path`` selects
+ the same executable everywhere: surrounding whitespace is ignored, and an
+ empty value or the bare ``claude`` name keeps the SDK's own resolution.
+ """
+ if cli_path is None:
+ return None
+ normalized = str(cli_path).strip()
+ if not normalized or normalized == "claude":
+ return None
+ return os.path.expanduser(normalized)
+
+
def build_claude_subprocess_env(
claude_cfg: Any,
base_env: Optional[Dict[str, str]] = None,