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): fail claude oauth on settings cleanup errors

cyhc405c88988b8
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 493fca339..6f9f3d4fb 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -1199,6 +1199,7 @@ class AgentAuthService:
)
ok, detail = await self._verify_login(flow)
if ok:
+ await self._clear_claude_settings_env_for_oauth()
await self._refresh_backend_runtime(flow.backend)
await self._send_message(
flow.context,
@@ -2389,8 +2390,8 @@ class AgentAuthService:
flow.state = "verifying"
ok, detail = await self._verify_web_login(flow.backend)
if ok:
- await self._refresh_backend_runtime(flow.backend)
await self._invoke_post_web_success_hook(flow.backend)
+ await self._refresh_backend_runtime(flow.backend)
flow.state = "success"
else:
flow.state = "failed"
@@ -2419,8 +2420,8 @@ class AgentAuthService:
flow.state = "verifying"
ok, detail = await self._verify_web_login(flow.backend)
if ok:
- await self._refresh_backend_runtime(flow.backend)
await self._invoke_post_web_success_hook(flow.backend)
+ await self._refresh_backend_runtime(flow.backend)
flow.state = "success"
else:
flow.state = "failed"
@@ -2486,24 +2487,30 @@ class AgentAuthService:
except Exception as err: # noqa: BLE001
logger.warning("post_web_success_hook failed for %s: %s", backend, err)
+ async def _clear_claude_settings_env_for_oauth(self) -> None:
+ try:
+ from vibe.claude_config import apply_claude_auth
+
+ await asyncio.to_thread(
+ apply_claude_auth,
+ auth_mode="oauth",
+ api_key=None,
+ base_url=None,
+ )
+ except Exception as err: # noqa: BLE001
+ raise RuntimeError(
+ "Failed to clear Claude Code settings env after OAuth flow; "
+ "stale ANTHROPIC_* values may still override OAuth."
+ ) from err
+
async def _persist_web_auth_mode(self, backend: str, auth_mode: str) -> None:
"""Update V2Config.agents.<backend>.auth_mode if the controller has
a writable config. Skipped silently in test contexts where the
stub controller exposes a non-savable config object.
"""
+ if backend == "claude" and auth_mode == "oauth":
+ await self._clear_claude_settings_env_for_oauth()
try:
- if backend == "claude" and auth_mode == "oauth":
- try:
- from vibe.claude_config import apply_claude_auth
-
- await asyncio.to_thread(
- apply_claude_auth,
- auth_mode="oauth",
- api_key=None,
- base_url=None,
- )
- except Exception as err: # noqa: BLE001
- logger.warning("Failed to clear Claude settings env after OAuth flow: %s", err)
config = getattr(self.controller, "config", None)
target = getattr(getattr(config, "agents", None), backend, None)
saver = getattr(config, "save", None) if config is not None else None
diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.py
index e6f1fb59e..0df81cf2f 100644
--- a/tests/test_agent_auth_service.py
+++ b/tests/test_agent_auth_service.py
@@ -844,6 +844,43 @@ class AgentAuthServiceTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("login is active again", controller.im_client.sent_messages[0][1].lower())
self.assertNotIn(flow.flow_key, service._flows)
+ async def test_wait_for_claude_completion_reports_settings_cleanup_failure(self):
+ controller = _StubController()
+ service = AgentAuthService(controller)
+ context = MessageContext(user_id="U1", channel_id="C1")
+ done_task = asyncio.create_task(asyncio.sleep(0))
+ await done_task
+ fake_client = SimpleNamespace()
+ flow = AgentAuthFlow(
+ flow_id="flow-claude-cleanup-fails",
+ backend="claude",
+ settings_key="C1",
+ initiator_user_id="U1",
+ context=context,
+ process=None,
+ reader_task=done_task,
+ waiter_task=done_task,
+ claude_client=fake_client,
+ )
+ service._flows[flow.flow_key] = flow
+ service._flows_by_id[flow.flow_id] = flow
+ service._send_claude_control_request = AsyncMock(return_value={})
+ service._verify_login = AsyncMock(return_value=(True, '{"loggedIn": true}'))
+ service._refresh_backend_runtime = AsyncMock()
+ service._disconnect_claude_client = AsyncMock()
+
+ with patch(
+ "vibe.claude_config.apply_claude_auth",
+ side_effect=OSError("settings locked"),
+ ):
+ await service._wait_for_claude_completion(flow)
+
+ service._refresh_backend_runtime.assert_not_awaited()
+ service._disconnect_claude_client.assert_awaited_once_with(fake_client)
+ self.assertIn("failed", controller.im_client.sent_button_messages[0][1].lower())
+ self.assertIn("Failed to clear Claude Code settings env", controller.im_client.sent_button_messages[0][1])
+ self.assertNotIn(flow.flow_key, service._flows)
+
async def test_start_opencode_process_closes_master_fd_on_spawn_failure(self):
controller = _StubController()
service = AgentAuthService(controller)
diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.py
index 3f63e1d92..d2bc3f1cf 100644
--- a/tests/test_web_oauth_flow.py
+++ b/tests/test_web_oauth_flow.py
@@ -193,18 +193,54 @@ def test_post_web_success_hook_invocation_when_set(
assert calls == ["codex"]
-def test_post_web_success_hook_swallows_exceptions(service: AgentAuthService) -> None:
+def test_post_web_success_hook_swallows_exceptions(
+ service: AgentAuthService,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
"""A misbehaving hook must not surface into the flow waiter."""
def hook(_backend: str) -> None:
raise RuntimeError("boom")
+ monkeypatch.setattr("vibe.claude_config.apply_claude_auth", lambda **_kwargs: None)
service._post_web_success_hook = hook
# Should NOT raise.
_run(service._invoke_post_web_success_hook("claude"))
-def test_post_web_success_hook_unset_is_safe(service: AgentAuthService) -> None:
+def test_claude_oauth_settings_cleanup_failure_fails_web_flow(
+ service: AgentAuthService,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ fake_client = object()
+ flow = WebAuthFlow(
+ flow_id="claude-cleanup-fails",
+ backend="claude",
+ claude_client=fake_client,
+ )
+ service._send_claude_control_request = AsyncMock(return_value={})
+ service._verify_web_login = AsyncMock(return_value=(True, '{"loggedIn": true}'))
+ service._refresh_backend_runtime = AsyncMock()
+ service._disconnect_claude_client = AsyncMock()
+
+ def fail_cleanup(**_kwargs):
+ raise OSError("settings locked")
+
+ monkeypatch.setattr("vibe.claude_config.apply_claude_auth", fail_cleanup)
+
+ _run(service._wait_for_claude_completion_web(flow))
+
+ assert flow.state == "failed"
+ assert "Failed to clear Claude Code settings env" in (flow.error or "")
+ service._refresh_backend_runtime.assert_not_awaited()
+ service._disconnect_claude_client.assert_awaited_once_with(fake_client)
+
+
+def test_post_web_success_hook_unset_is_safe(
+ service: AgentAuthService,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr("vibe.claude_config.apply_claude_auth", lambda **_kwargs: None)
service._post_web_success_hook = None
_run(service._invoke_post_web_success_hook("claude"))
@@ -346,6 +382,7 @@ def test_remove_web_auth_runs_logout_and_returns_ok(
# path mocks must yield ``(True, None)``.
run_cmd = AsyncMock(return_value=(True, None))
monkeypatch.setattr(service, "_run_utility_command", run_cmd)
+ monkeypatch.setattr("vibe.claude_config.apply_claude_auth", lambda **_kwargs: None)
hook_calls: list[str] = []
service._post_web_success_hook = lambda b: hook_calls.append(b)
@@ -382,6 +419,7 @@ def test_remove_web_auth_surfaces_logout_failure(
# cleaned up manually.
run_cmd = AsyncMock(return_value=(False, "exit 1: not logged in"))
monkeypatch.setattr(service, "_run_utility_command", run_cmd)
+ monkeypatch.setattr("vibe.claude_config.apply_claude_auth", lambda **_kwargs: None)
result = _run(service.remove_web_auth("claude"))
assert result["ok"] is True
assert result["partial"] is True