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 Claude OAuth login state
Call White63b3dd050a27
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex e040fd699..059fad31e 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -287,12 +287,34 @@ class AgentAuthFlow:device_code: str | None = Noneprovider: str | None = Nonelast_status_text: str | None = None+ force_oauth: bool = False+ claude_oauth_attempt: "ClaudeOAuthAttempt | None" = None@propertydef flow_key(self) -> str:return f"{self.settings_key}:{self.backend}"+@dataclass+class ClaudeOAuthBatch:+ backup: dict[str, str] | None+ attempts: dict[int, "ClaudeOAuthAttempt"] = field(default_factory=dict)+ committed: bool = False+ durable_backup: bool = False+++@dataclass+class ClaudeOAuthAttempt:+ attempt_id: int+ batch: ClaudeOAuthBatch+ active: bool = True+ succeeded: bool = False++ @property+ def settings_backup(self) -> dict[str, str] | None:+ return self.batch.backup++# Web Settings → Backends OAuth flows live alongside the IM ``AgentAuthFlow``# but share none of its IM coupling: no MessageContext, no ``_send_message``,# no settings_key. State is exposed to the browser via a polling endpoint, so@@ -320,6 +342,7 @@ class WebAuthFlow:# — accessing a runtime-assigned attribute on Claude/Codex flows# would AttributeError out and 500 the start endpoint.provider: str | None = None+ claude_oauth_attempt: ClaudeOAuthAttempt | None = Nonecreated_at: float = field(default_factory=time.time)# Timestamp the flow first entered a terminal state (success /# failed / cancelled). ``None`` while the flow is still in@@ -343,6 +366,10 @@ class AgentAuthService:# context exists for them, so they cannot live in ``_flows``.self._web_flows: dict[str, WebAuthFlow] = {}self._web_flow_lock = asyncio.Lock()+ self._claude_oauth_attempt_counter = 0+ self._claude_oauth_batch: ClaudeOAuthBatch | None = None+ self._claude_oauth_lock = asyncio.Lock()+ self._recover_interrupted_claude_oauth_settings_backup()# Optional callable invoked after a successful *web* auth flow so# the UI-server process can ask the long-running controller to# reload V2Config-backed credentials. The hook receives ``(backend,)``@@ -402,6 +429,32 @@ class AgentAuthService:cli_path = getattr(backend_cfg, "cli_path", None) or getattr(backend_cfg, "binary", None)return cli_path or backend+ def _build_claude_full_subprocess_env(self, *, force_oauth: bool = False) -> dict[str, str]:+ """Return a complete environment for direct Claude CLI subprocesses.++ ``build_claude_subprocess_env`` intentionally returns only the+ Anthropic/Claude variables that should be visible to Claude SDK clients.+ For direct ``create_subprocess_exec(..., env=...)`` calls we need a full+ process env. Start from ``os.environ`` for PATH/etc, remove every+ Anthropic/Claude variable, then layer back only the allowed values so+ OAuth-mode filtering really deletes stale shell credentials.+ """+ env_override = dict(os.environ)+ for key in list(env_override.keys()):+ if key.startswith("ANTHROPIC_") or key.startswith("CLAUDE_"):+ env_override.pop(key, None)++ from vibe.claude_config import build_claude_subprocess_env++ env_override.update(+ build_claude_subprocess_env(+ self._resolve_backend_config("claude"),+ base_env=os.environ,+ force_oauth=force_oauth,+ )+ )+ return env_override+async def _resolve_opencode_provider(self, context: MessageContext) -> str:override_agent = Noneoverride_model = None@@ -581,69 +634,75 @@ class AgentAuthService:f"⏳ {self._t('command.setup.starting', backend=resolved_backend)}",)- if resolved_backend == "codex":- process = await self._start_codex_process(force_reset=force_reset)- flow = AgentAuthFlow(- flow_id=uuid.uuid4().hex[:12],- backend=resolved_backend,- settings_key=self._get_settings_key(context),- initiator_user_id=context.user_id,- context=context,- process=process,- reader_task=asyncio.create_task(asyncio.sleep(0)),- waiter_task=asyncio.create_task(asyncio.sleep(0)),- )- elif resolved_backend == "claude":- client, manual_url = await self._start_claude_control_flow(- context,- force_reset=force_reset,- login_with_claude_ai=claude_login_method != "console",- )- flow = AgentAuthFlow(- flow_id=uuid.uuid4().hex[:12],- backend=resolved_backend,- settings_key=self._get_settings_key(context),- initiator_user_id=context.user_id,- context=context,- process=None,- reader_task=asyncio.create_task(asyncio.sleep(0)),- waiter_task=asyncio.create_task(asyncio.sleep(0)),- claude_client=client,- login_prompt_sent=True,- url=manual_url,- )- else:- provider = await self._resolve_opencode_provider(context)- if self._supports_direct_opencode_api_key_setup(provider):+ try:+ if resolved_backend == "codex":+ process = await self._start_codex_process(force_reset=force_reset)flow = AgentAuthFlow(flow_id=uuid.uuid4().hex[:12],backend=resolved_backend,settings_key=self._get_settings_key(context),initiator_user_id=context.user_id,context=context,- process=None,+ process=process,reader_task=asyncio.create_task(asyncio.sleep(0)),waiter_task=asyncio.create_task(asyncio.sleep(0)),- provider=provider,- awaiting_code=True,- login_prompt_sent=True,- code_prompt_sent=True,- url=self._get_opencode_setup_url(provider),)- else:- process, master_fd, provider = await self._start_opencode_process(context, force_reset=force_reset)+ elif resolved_backend == "claude":+ client, manual_url, attempt = await self._start_claude_control_flow(+ context,+ force_reset=force_reset,+ login_with_claude_ai=claude_login_method != "console",+ )flow = AgentAuthFlow(flow_id=uuid.uuid4().hex[:12],backend=resolved_backend,settings_key=self._get_settings_key(context),initiator_user_id=context.user_id,context=context,- process=process,+ process=None,reader_task=asyncio.create_task(asyncio.sleep(0)),waiter_task=asyncio.create_task(asyncio.sleep(0)),- pty_master_fd=master_fd,- provider=provider,+ claude_client=client,+ login_prompt_sent=True,+ url=manual_url,+ claude_oauth_attempt=attempt,)+ else:+ provider = await self._resolve_opencode_provider(context)+ if self._supports_direct_opencode_api_key_setup(provider):+ flow = AgentAuthFlow(+ flow_id=uuid.uuid4().hex[:12],+ backend=resolved_backend,+ settings_key=self._get_settings_key(context),+ initiator_user_id=context.user_id,+ context=context,+ process=None,+ reader_task=asyncio.create_task(asyncio.sleep(0)),+ waiter_task=asyncio.create_task(asyncio.sleep(0)),+ provider=provider,+ awaiting_code=True,+ login_prompt_sent=True,+ code_prompt_sent=True,+ url=self._get_opencode_setup_url(provider),+ )+ else:+ process, master_fd, provider = await self._start_opencode_process(context, force_reset=force_reset)+ flow = AgentAuthFlow(+ flow_id=uuid.uuid4().hex[:12],+ backend=resolved_backend,+ settings_key=self._get_settings_key(context),+ initiator_user_id=context.user_id,+ context=context,+ process=process,+ reader_task=asyncio.create_task(asyncio.sleep(0)),+ waiter_task=asyncio.create_task(asyncio.sleep(0)),+ pty_master_fd=master_fd,+ provider=provider,+ )+ except Exception as err: # noqa: BLE001+ logger.error("Agent auth setup failed to start for %s: %s", resolved_backend, err, exc_info=True)+ await self._send_setup_start_failure(context, resolved_backend, str(err))+ returnself._flows[flow_key] = flowself._flows_by_id[flow.flow_id] = flow@@ -825,6 +884,19 @@ class AgentAuthService:fallback = fallback_text or textreturn await im_client.send_message(context, fallback)+ async def _send_setup_start_failure(+ self,+ context: MessageContext,+ backend: str,+ detail: str,+ ) -> None:+ await self._send_message_with_button(+ context,+ f"❌ {self._t('command.setup.failed', backend=backend, detail=detail)}",+ button_text=self._t("button.resetOAuth"),+ callback_data=f"auth_setup:{backend}",+ )+async def _prompt_claude_login_method(self, context: MessageContext) -> None:text = self._t("command.setup.claudeMethodPrompt")keyboard = InlineKeyboard(@@ -857,15 +929,19 @@ class AgentAuthService:*,force_reset: bool,login_with_claude_ai: bool,- ) -> tuple[ClaudeSDKClient, str]:+ ) -> tuple[ClaudeSDKClient, str, ClaudeOAuthAttempt]:if not CLAUDE_SDK_AVAILABLE:raise ModuleNotFoundError("claude_agent_sdk is required for Claude setup flows")if force_reset:await self._run_utility_command(self._get_cli_binary("claude"), "auth", "logout")-- client = await self._create_claude_control_client(context)+ # Claude Code re-applies ``settings.json`` env at startup, so an+ # OAuth flow must clear stale API-key settings before the control+ # client or follow-up probes launch.+ attempt = await self._begin_claude_oauth_attempt()+ client = Nonetry:+ client = await self._create_claude_control_client(context)response = await self._send_claude_control_request(client,{@@ -874,14 +950,18 @@ class AgentAuthService:},)except Exception:- await self._disconnect_claude_client(client)+ await self._finish_claude_oauth_attempt(attempt, succeeded=False)+ if client is not None:+ await self._disconnect_claude_client(client)raisemanual_url = str(response.get("manualUrl") or "").strip()if not manual_url:- await self._disconnect_claude_client(client)+ await self._finish_claude_oauth_attempt(attempt, succeeded=False)+ if client is not None:+ await self._disconnect_claude_client(client)raise RuntimeError("Claude auth flow did not return a manual login URL")- return client, manual_url+ return client, manual_url, attemptasync def _create_claude_control_client(self, context: Optional[MessageContext] = None@@ -1234,15 +1314,18 @@ class AgentAuthService:),timeout=self.setup_timeout_seconds,)+ flow.force_oauth = Trueok, detail = await self._verify_login(flow)if ok:- await self._clear_claude_settings_env_for_oauth()+ await self._persist_backend_auth_mode(flow.backend, "oauth")+ await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=True)await self._refresh_backend_runtime(flow.backend)await self._send_message(flow.context,f"✅ {self._t('command.setup.success', backend=flow.backend)}",)else:+ await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=False)detail_text = detail or self._t("command.setup.unknownFailure")await self._send_message_with_button(flow.context,@@ -1251,6 +1334,7 @@ class AgentAuthService:callback_data=f"auth_setup:{flow.backend}",)except asyncio.TimeoutError:+ await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=False)await self._send_message_with_button(flow.context,f"❌ {self._t('command.setup.failed', backend=flow.backend, detail=self._t('command.setup.timedOut', backend=flow.backend))}",@@ -1258,8 +1342,10 @@ class AgentAuthService:callback_data=f"auth_setup:{flow.backend}",)except asyncio.CancelledError:+ await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=False)raiseexcept Exception as err: # noqa: BLE001+ await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=False)logger.error("Claude auth flow failed: %s", err, exc_info=True)await self._send_message_with_button(flow.context,@@ -1302,6 +1388,10 @@ class AgentAuthService:return False, self._describe_opencode_cli_failure(process.returncode, text)return (verify_opencode_auth_list_output(text, flow.provider), text)+ force_oauth = bool(getattr(flow, "force_oauth", False))+ settings_backup: dict[str, str] | None = None+ if force_oauth:+ settings_backup = await self._prepare_claude_oauth_probe(flow.claude_oauth_attempt)binary = self._get_cli_binary("claude")process = await asyncio.create_subprocess_exec(binary,@@ -1310,14 +1400,20 @@ class AgentAuthService:"--json",stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.STDOUT,+ env=self._build_claude_full_subprocess_env(force_oauth=force_oauth),)stdout, _ = await process.communicate()text = stdout.decode("utf-8", errors="replace").strip()try:payload = json.loads(text)except json.JSONDecodeError:+ if force_oauth and flow.claude_oauth_attempt is None:+ await self._restore_transient_claude_oauth_probe_backup(settings_backup)return False, text- return (bool(payload.get("loggedIn")), text)+ logged_in = bool(payload.get("loggedIn"))+ if force_oauth and not logged_in and flow.claude_oauth_attempt is None:+ await self._restore_transient_claude_oauth_probe_backup(settings_backup)+ return (logged_in, text)def _describe_opencode_cli_failure(self, returncode: int, text: str) -> str:detail = text or ""@@ -1643,6 +1739,7 @@ class AgentAuthService:return mapped if mapped in CLAUDE_LOGIN_METHODS else Noneasync def _terminate_flow(self, flow: AgentAuthFlow) -> None:+ await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=False)if flow.waiter_task and not flow.waiter_task.done():flow.waiter_task.cancel()try:@@ -1748,12 +1845,13 @@ class AgentAuthService:flow.reader_task = asyncio.create_task(self._read_codex_output_web(flow))flow.waiter_task = asyncio.create_task(self._wait_for_codex_completion_web(flow))elif backend == "claude":- client, manual_url = await self._start_claude_control_flow(+ client, manual_url, attempt = await self._start_claude_control_flow(context=None,force_reset=force_reset,login_with_claude_ai=True,)flow.claude_client = client+ flow.claude_oauth_attempt = attemptflow.url = manual_urlflow.awaiting_code = Trueflow.state = "awaiting_code"@@ -1764,6 +1862,8 @@ class AgentAuthService:await self._start_opencode_oauth_web(flow, provider_id.strip())except Exception as err: # noqa: BLE001logger.error("Web auth start failed for %s: %s", backend, err, exc_info=True)+ if backend == "claude":+ await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=False)flow.state = "failed"flow.error = str(err)return flow@@ -1988,20 +2088,20 @@ class AgentAuthService:if isinstance(model, str) and model.strip():cmd.extend(["--model", model.strip()])cmd.append(prompt)- env_override = dict(os.environ)- # Layer V2Config-driven env on top so the test reflects what- # the live IM session would do at launch.+ backend_cfg = self._resolve_backend_config("claude")+ auth_mode = getattr(backend_cfg, "auth_mode", None)+ auth_mode_set = bool(getattr(backend_cfg, "auth_mode_set", False))+ if auth_mode == "oauth" and auth_mode_set:+ try:+ await self._clear_claude_settings_env_for_oauth()+ except Exception as err: # noqa: BLE001+ return {"ok": False, "error": "settings_cleanup_failed", "detail": str(err)}try:- from vibe.claude_config import build_claude_subprocess_env-- env_override.update(- build_claude_subprocess_env(- self._resolve_backend_config("claude"),- base_env=env_override,- )- )- except Exception:- pass+ env_override = self._build_claude_full_subprocess_env()+ except Exception as err: # noqa: BLE001+ if auth_mode == "oauth" and auth_mode_set:+ return {"ok": False, "error": "spawn_failed", "detail": str(err)}+ env_override = dict(os.environ)else:# Codex single-shot mode. ``--skip-git-repo-check`` bypasses# Codex's per-project trust gate. We also force@@ -2581,7 +2681,7 @@ class AgentAuthService:flow.error = last_line[:400]returnflow.state = "verifying"- ok, detail = await self._verify_web_login(flow.backend)+ ok, detail = await self._verify_web_login(flow.backend, force_oauth=flow.backend == "claude")if ok:await self._invoke_post_web_success_hook(flow.backend)await self._refresh_backend_runtime(flow.backend)@@ -2611,20 +2711,29 @@ class AgentAuthService:timeout=self.setup_timeout_seconds,)flow.state = "verifying"- ok, detail = await self._verify_web_login(flow.backend)+ ok, detail = await self._verify_web_login(+ flow.backend,+ force_oauth=True,+ claude_oauth_attempt=flow.claude_oauth_attempt,+ )if ok:await self._invoke_post_web_success_hook(flow.backend)+ await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=True)await self._refresh_backend_runtime(flow.backend)flow.state = "success"else:+ await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=False)flow.state = "failed"flow.error = detail or "unknown_failure"except asyncio.TimeoutError:+ await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=False)flow.state = "failed"flow.error = "timed_out"except asyncio.CancelledError:+ await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=False)raiseexcept Exception as err: # noqa: BLE001+ await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=False)logger.error("Web Claude auth flow failed: %s", err, exc_info=True)flow.state = "failed"flow.error = str(err)@@ -2633,7 +2742,13 @@ class AgentAuthService:await self._disconnect_claude_client(flow.claude_client)flow.claude_client = None- async def _verify_web_login(self, backend: str) -> tuple[bool, str]:+ async def _verify_web_login(+ self,+ backend: str,+ *,+ force_oauth: bool = False,+ claude_oauth_attempt: ClaudeOAuthAttempt | None = None,+ ) -> tuple[bool, str]:"""Re-run the same CLI status probes ``_verify_login`` uses for IM.Builds a temporary IM-shaped ``AgentAuthFlow`` shell so the existing@@ -2651,6 +2766,8 @@ class AgentAuthService:reader_task=asyncio.create_task(asyncio.sleep(0)),waiter_task=asyncio.create_task(asyncio.sleep(0)),)+ dummy.force_oauth = force_oauth+ dummy.claude_oauth_attempt = claude_oauth_attempttry:return await self._verify_login(dummy)finally:@@ -2671,7 +2788,7 @@ class AgentAuthService:# field (auth is per-provider, not global), so persisting one# would add a stray attribute and could mislead future readers.if backend != "opencode":- await self._persist_web_auth_mode(backend, "oauth")+ await self._persist_backend_auth_mode(backend, "oauth")hook = self._post_web_success_hookif not callable(hook):return@@ -2696,6 +2813,191 @@ class AgentAuthService:"stale ANTHROPIC_* values may still override OAuth.") from err+ async def _read_pending_claude_oauth_settings_backup(+ self,+ ) -> dict[str, str] | None:+ try:+ from vibe.claude_config import read_claude_oauth_settings_backup++ return await asyncio.to_thread(read_claude_oauth_settings_backup)+ except Exception as err: # noqa: BLE001+ logger.warning("Failed to read pending Claude OAuth settings backup: %s", err)+ return None++ def _recover_interrupted_claude_oauth_settings_backup(self) -> None:+ try:+ from vibe.claude_config import (+ clear_claude_oauth_settings_backup,+ read_claude_oauth_settings_backup,+ restore_claude_settings_env,+ )++ backup = read_claude_oauth_settings_backup()+ if not backup:+ return+ restore_claude_settings_env(backup)+ clear_claude_oauth_settings_backup()+ except Exception as err: # noqa: BLE001+ logger.warning("Failed to recover interrupted Claude OAuth settings backup: %s", err)++ async def _read_rollback_claude_oauth_settings_backup(+ self,+ ) -> dict[str, str] | None:+ return await self._read_pending_claude_oauth_settings_backup()++ async def _write_pending_claude_oauth_settings_backup(+ self,+ settings_backup: dict[str, str] | None,+ ) -> bool:+ if not settings_backup:+ return False+ try:+ from vibe.claude_config import write_claude_oauth_settings_backup++ await asyncio.to_thread(write_claude_oauth_settings_backup, settings_backup)+ return True+ except Exception as err: # noqa: BLE001+ raise RuntimeError(+ "Failed to persist Claude Code settings backup before OAuth flow; "+ "existing API-key settings were not changed."+ ) from err++ async def _clear_pending_claude_oauth_settings_backup(self) -> None:+ try:+ from vibe.claude_config import clear_claude_oauth_settings_backup++ await asyncio.to_thread(clear_claude_oauth_settings_backup)+ except Exception as err: # noqa: BLE001+ logger.warning("Failed to clear pending Claude OAuth settings backup: %s", err)++ async def _temporarily_clear_claude_settings_env_for_oauth(+ self,+ *,+ persist_backup: bool = False,+ existing_backup: dict[str, str] | None = None,+ ) -> dict[str, str] | None:+ try:+ from vibe.claude_config import read_claude_settings_env++ settings_backup = await asyncio.to_thread(read_claude_settings_env)+ except Exception as err: # noqa: BLE001+ raise RuntimeError(+ "Failed to read Claude Code settings env before OAuth flow; "+ "stale ANTHROPIC_* values may still override OAuth."+ ) from err+ effective_backup = existing_backup or settings_backup or None+ if persist_backup and settings_backup and not existing_backup:+ await self._write_pending_claude_oauth_settings_backup(settings_backup)+ await self._clear_claude_settings_env_for_oauth()+ return effective_backup++ async def _restore_claude_settings_env_after_oauth_failure(+ self, settings_backup: dict[str, str] | None+ ) -> bool:+ if not settings_backup:+ return True+ try:+ from vibe.claude_config import restore_claude_settings_env++ await asyncio.to_thread(+ restore_claude_settings_env,+ settings_backup,+ )+ return True+ except Exception as err: # noqa: BLE001+ logger.warning("Failed to restore Claude settings env after OAuth failure: %s", err)+ return False++ async def _restore_transient_claude_oauth_probe_backup(+ self,+ settings_backup: dict[str, str] | None,+ ) -> None:+ if not settings_backup:+ return+ async with self._claude_oauth_lock:+ if self._claude_oauth_batch is not None:+ return+ await self._restore_claude_settings_env_after_oauth_failure(settings_backup)++ async def _begin_claude_oauth_attempt(self) -> ClaudeOAuthAttempt:+ async with self._claude_oauth_lock:+ batch = self._claude_oauth_batch+ new_batch = batch is None or batch.committed or not batch.attempts+ existing_backup = None+ if new_batch:+ existing_backup = await self._read_rollback_claude_oauth_settings_backup()+ settings_backup = await self._temporarily_clear_claude_settings_env_for_oauth(+ persist_backup=new_batch,+ existing_backup=existing_backup,+ )+ if new_batch:+ batch = ClaudeOAuthBatch(+ backup=dict(settings_backup or {}) or None,+ durable_backup=bool(existing_backup or settings_backup),+ )+ self._claude_oauth_batch = batch+ elif batch.backup is None and settings_backup:+ batch.backup = dict(settings_backup)++ self._claude_oauth_attempt_counter += 1+ attempt = ClaudeOAuthAttempt(+ attempt_id=self._claude_oauth_attempt_counter,+ batch=batch,+ )+ batch.attempts[attempt.attempt_id] = attempt+ return attempt++ async def _prepare_claude_oauth_probe(+ self,+ attempt: ClaudeOAuthAttempt | None,+ ) -> dict[str, str] | None:+ async with self._claude_oauth_lock:+ settings_backup = await self._temporarily_clear_claude_settings_env_for_oauth()+ if attempt is None:+ return settings_backup+ if attempt.batch.backup is None and settings_backup:+ attempt.batch.backup = dict(settings_backup)+ return attempt.settings_backup++ async def _finish_claude_oauth_attempt(+ self,+ attempt: ClaudeOAuthAttempt | None,+ *,+ succeeded: bool,+ ) -> None:+ async with self._claude_oauth_lock:+ if attempt is None or not attempt.active:+ return++ attempt.active = False+ attempt.succeeded = succeeded+ batch = attempt.batch+ batch.attempts.pop(attempt.attempt_id, None)+ if succeeded:+ had_durable_backup = batch.durable_backup+ batch.committed = True+ batch.backup = None+ batch.durable_backup = False+ if self._claude_oauth_batch is batch and not batch.attempts:+ self._claude_oauth_batch = None+ if had_durable_backup:+ await self._clear_pending_claude_oauth_settings_backup()+ return++ if not batch.attempts:+ backup = batch.backup+ had_durable_backup = batch.durable_backup+ should_restore = not batch.committed+ batch.backup = None+ batch.durable_backup = False+ if self._claude_oauth_batch is batch:+ self._claude_oauth_batch = None+ restore_ok = True+ if should_restore:+ restore_ok = await self._restore_claude_settings_env_after_oauth_failure(backup)+ if restore_ok and had_durable_backup:+ await self._clear_pending_claude_oauth_settings_backup()+async def _clear_claude_settings_env_for_logout(self) -> str | None:try:await self._clear_claude_settings_env_for_oauth()@@ -2704,17 +3006,21 @@ class AgentAuthService:return str(err)return None- 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.- """+ async def _persist_backend_auth_mode(self, backend: str, auth_mode: str) -> None:+ """Persist V2Config.agents.<backend>.auth_mode for web and IM flows."""if backend == "claude" and auth_mode == "oauth":await self._clear_claude_settings_env_for_oauth()try: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+ loaded_config = None+ if target is None or not callable(saver):+ from config.v2_config import V2Config++ loaded_config = V2Config.load()+ target = getattr(getattr(loaded_config, "agents", None), backend, None)+ saver = getattr(loaded_config, "save", None)if target is None or not callable(saver):return# An explicit OAuth save must also flip ``auth_mode_set``@@ -2745,6 +3051,13 @@ class AgentAuthService:if needs_marker_write:target.auth_mode_set = Truesaver()+ if loaded_config is not None and config is not None:+ compat_target = getattr(config, backend, None)+ if compat_target is not None:+ if needs_mode_write:+ setattr(compat_target, "auth_mode", auth_mode)+ if needs_marker_write:+ setattr(compat_target, "auth_mode_set", True)except Exception as err: # noqa: BLE001logger.warning("Failed to persist auth_mode=%s after web flow for %s: %s",@@ -2758,6 +3071,7 @@ class AgentAuthService:final_state: WebFlowState,error: str | None = None,) -> None:+ await self._finish_claude_oauth_attempt(flow.claude_oauth_attempt, succeeded=False)if flow.reader_task and not flow.reader_task.done():flow.reader_task.cancel()try:diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex 1e5defc6c..91346e307 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -119,6 +119,13 @@ scenarios:layer: scenariobackend: codextest: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_failed_codex_setup_does_not_leave_stale_runtime_for_next_attempt+ - id: AUTH-SETUP-208+ name: Claude startup cleanup failure emits a reset path+ status: covered+ kind: retry+ layer: scenario+ backend: claude+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_claude_startup_cleanup_failure_emits_reset_path- id: AUTH-SETUP-901name: Codex setup success refreshes runtime before the next turnstatus: covered@@ -135,5 +142,4 @@ scenarios:test: tests/test_claude_agent_sessions.py::test_assistant_auth_error_without_is_api_error_flag_still_triggers_recoverynext_priority:- AUTH-SETUP-106- - AUTH-SETUP-208- AUTH-SETUP-301diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex 0a5c38581..f9970ed5d 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -77,6 +77,33 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):ScenarioExpect.button_callback_contains(harness, "auth_setup:codex")ScenarioExpect.flow_missing(harness, "C1:codex")+ async def test_claude_startup_cleanup_failure_emits_reset_path(self):+ """Scenario: AUTH-SETUP-208"""+ harness = AuthSetupScenarioHarness()+ runner = ScenarioRunner(harness)+ harness.service._start_claude_control_flow = AsyncMock(+ side_effect=RuntimeError("Failed to clear Claude Code settings env")+ )++ await runner.run(+ ScenarioStep(+ "start_setup",+ lambda h: h.service.start_setup(+ h.context,+ backend="claude",+ force_reset=True,+ claude_login_method="console",+ ),+ ),+ )++ ScenarioExpect.step_history(runner, ["start_setup"])+ ScenarioExpect.text_contains(harness, "starting claude", index=0)+ ScenarioExpect.text_contains(harness, "failed", index=1)+ ScenarioExpect.text_contains(harness, "Failed to clear Claude Code settings env", index=1)+ ScenarioExpect.button_callback_contains(harness, "auth_setup:claude")+ ScenarioExpect.flow_missing(harness, "C1:claude")+async def test_codex_reentry_scenario_replaces_existing_flow(self):"""Scenario: AUTH-SETUP-201"""harness = AuthSetupScenarioHarness()@@ -207,7 +234,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):runner = ScenarioRunner(harness)callback_payloads = []harness.service._start_claude_control_flow = AsyncMock(- return_value=(fake_client, "https://platform.claude.com/oauth/code/callback")+ return_value=(fake_client, "https://platform.claude.com/oauth/code/callback", None))harness.service._wait_for_claude_completion = AsyncMock(return_value=None)harness.service._send_claude_callback = AsyncMock(@@ -254,7 +281,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):runner = ScenarioRunner(harness)harness.service._start_claude_control_flow = AsyncMock(- return_value=(fake_client, "https://platform.claude.com/oauth/code/callback")+ return_value=(fake_client, "https://platform.claude.com/oauth/code/callback", None))async def fake_control_request(client, request, timeout=900.0):@@ -317,7 +344,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):runner = ScenarioRunner(harness)harness.service._start_claude_control_flow = AsyncMock(- return_value=(fake_client, "https://platform.claude.com/oauth/code/callback")+ return_value=(fake_client, "https://platform.claude.com/oauth/code/callback", None))async def fake_control_request(client, request, timeout=900.0):@@ -374,7 +401,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):fake_client = object()runner = ScenarioRunner(harness)harness.service._start_claude_control_flow = AsyncMock(- return_value=(fake_client, "https://platform.claude.com/oauth/code/callback")+ return_value=(fake_client, "https://platform.claude.com/oauth/code/callback", None))harness.service._wait_for_claude_completion = AsyncMock(return_value=None)harness.service._send_claude_callback = AsyncMock()@@ -409,7 +436,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):runner = ScenarioRunner(harness)harness.service._start_claude_control_flow = AsyncMock(- return_value=(fake_client, "https://platform.claude.com/oauth/code/callback")+ return_value=(fake_client, "https://platform.claude.com/oauth/code/callback", None))harness.service._resolve_opencode_provider = AsyncMock(return_value="opencode")harness.service._install_opencode_api_key = AsyncMock()@@ -483,7 +510,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):harness.service.setup_timeout_seconds = 0.01harness.service._start_claude_control_flow = AsyncMock(- return_value=(fake_client, "https://platform.claude.com/oauth/code/callback")+ return_value=(fake_client, "https://platform.claude.com/oauth/code/callback", None))async def fake_control_request(client, request, timeout=900.0):@@ -649,8 +676,8 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):harness.service.setup_timeout_seconds = 0.01harness.service._start_claude_control_flow = AsyncMock(side_effect=[- (first_client, "https://platform.claude.com/oauth/code/callback?attempt=1"),- (second_client, "https://platform.claude.com/oauth/code/callback?attempt=2"),+ (first_client, "https://platform.claude.com/oauth/code/callback?attempt=1", None),+ (second_client, "https://platform.claude.com/oauth/code/callback?attempt=2", None),])diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.pyindex bb7ae6922..87eb2eb26 100644--- a/tests/test_agent_auth_service.py+++ b/tests/test_agent_auth_service.py@@ -21,6 +21,22 @@ from modules.claude_sdk_compat import CLAUDE_SDK_MAX_BUFFER_SIZEfrom modules.im import MessageContext+class _IsolatedClaudeConfigDirMixin:+ def setUp(self):+ super().setUp()+ self._claude_config_dir_tmp = tempfile.TemporaryDirectory()+ self._previous_claude_config_dir = os.environ.get("CLAUDE_CONFIG_DIR")+ os.environ["CLAUDE_CONFIG_DIR"] = str(Path(self._claude_config_dir_tmp.name) / ".claude")++ def tearDown(self):+ if self._previous_claude_config_dir is None:+ os.environ.pop("CLAUDE_CONFIG_DIR", None)+ else:+ os.environ["CLAUDE_CONFIG_DIR"] = self._previous_claude_config_dir+ self._claude_config_dir_tmp.cleanup()+ super().tearDown()++@contextmanagerdef _temporary_vibe_home(tmp_path: Path):previous_home = os.environ.get("VIBE_REMOTE_HOME")@@ -48,9 +64,9 @@ class _StubIMClient:return "btn-1"-class _StubController:+class _StubConfig(SimpleNamespace):def __init__(self):- self.config = SimpleNamespace(+ super().__init__(platform="slack",language="en",agents=SimpleNamespace(@@ -58,7 +74,16 @@ class _StubController:claude=SimpleNamespace(cli_path="claude"),opencode=SimpleNamespace(cli_path="opencode"),),+ save_calls=0,)++ def save(self):+ self.save_calls += 1+++class _StubController:+ def __init__(self):+ self.config = _StubConfig()self.im_client = _StubIMClient()self.agent_service = SimpleNamespace(agents={})self.settings_manager = SimpleNamespace(sessions={})@@ -87,7 +112,7 @@ class _StubController:return (None, None, None)-class AgentAuthServiceTests(unittest.IsolatedAsyncioTestCase):+class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyncioTestCase):async def test_handle_setup_command_submits_code(self):controller = _StubController()service = AgentAuthService(controller)@@ -253,7 +278,7 @@ class AgentAuthServiceTests(unittest.IsolatedAsyncioTestCase):service = AgentAuthService(controller)context = MessageContext(user_id="U1", channel_id="C1")mock_client = SimpleNamespace()- service._start_claude_control_flow = AsyncMock(return_value=(mock_client, "https://platform.claude.com/oauth/code"))+ service._start_claude_control_flow = AsyncMock(return_value=(mock_client, "https://platform.claude.com/oauth/code", None))service._wait_for_claude_completion = AsyncMock()await service.start_setup(context, backend="claude", force_reset=True, claude_login_method="console")@@ -269,6 +294,65 @@ class AgentAuthServiceTests(unittest.IsolatedAsyncioTestCase):self.assertIs(flow.claude_client, mock_client)self.assertTrue(flow.login_prompt_sent)+ async def test_start_setup_reports_claude_start_failure(self):+ controller = _StubController()+ service = AgentAuthService(controller)+ context = MessageContext(user_id="U1", channel_id="C1")+ service._start_claude_control_flow = AsyncMock(+ side_effect=RuntimeError("Failed to clear Claude Code settings env")+ )++ await service.start_setup(context, backend="claude", force_reset=True, claude_login_method="console")++ self.assertEqual(len(controller.im_client.sent_messages), 1)+ self.assertEqual(len(controller.im_client.sent_button_messages), 1)+ _, text, keyboard = controller.im_client.sent_button_messages[0]+ self.assertIn("failed", text.lower())+ self.assertIn("Failed to clear Claude Code settings env", text)+ self.assertEqual(keyboard.buttons[0][0].callback_data, "auth_setup:claude")+ self.assertNotIn("C1:claude", service._flows)++ async def test_start_claude_control_flow_restores_settings_on_auth_start_failure(self):+ controller = _StubController()+ service = AgentAuthService(controller)+ context = MessageContext(user_id="U1", channel_id="C1")++ with tempfile.TemporaryDirectory() as home:+ claude_home = Path(home) / ".claude"+ claude_home.mkdir()+ previous_claude_config_dir = os.environ.get("CLAUDE_CONFIG_DIR")+ os.environ["CLAUDE_CONFIG_DIR"] = str(claude_home)+ try:+ from vibe.claude_config import read_claude_settings_env++ (claude_home / "settings.json").write_text(+ '{"env":{"ANTHROPIC_API_KEY":"sk-old","ANTHROPIC_BASE_URL":"https://relay.example"}}',+ encoding="utf-8",+ )+ service._create_claude_control_client = AsyncMock(return_value=SimpleNamespace())+ service._send_claude_control_request = AsyncMock(side_effect=RuntimeError("control failed"))+ service._disconnect_claude_client = AsyncMock()++ with self.assertRaisesRegex(RuntimeError, "control failed"):+ await service._start_claude_control_flow(+ context,+ force_reset=False,+ login_with_claude_ai=True,+ )++ self.assertEqual(+ read_claude_settings_env(),+ {+ "ANTHROPIC_API_KEY": "sk-old",+ "ANTHROPIC_BASE_URL": "https://relay.example",+ },+ )+ finally:+ if previous_claude_config_dir is None:+ os.environ.pop("CLAUDE_CONFIG_DIR", None)+ else:+ os.environ["CLAUDE_CONFIG_DIR"] = previous_claude_config_dir+async def test_start_setup_prompts_for_claude_login_method_when_unspecified(self):controller = _StubController()service = AgentAuthService(controller)@@ -882,18 +966,76 @@ class AgentAuthServiceTests(unittest.IsolatedAsyncioTestCase):service._refresh_backend_runtime = AsyncMock()service._disconnect_claude_client = AsyncMock()- await service._wait_for_claude_completion(flow)+ with patch("vibe.claude_config.apply_claude_auth") as cleanup:+ await service._wait_for_claude_completion(flow)service._send_claude_control_request.assert_awaited_once_with(flow.claude_client,{"subtype": "claude_oauth_wait_for_completion"},timeout=service.setup_timeout_seconds,)+ cleanup.assert_called()+ self.assertEqual(controller.config.agents.claude.auth_mode, "oauth")+ self.assertTrue(controller.config.agents.claude.auth_mode_set)+ self.assertEqual(controller.config.save_calls, 1)service._refresh_backend_runtime.assert_awaited_once_with("claude")service._disconnect_claude_client.assert_awaited_once_with(flow.claude_client)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_persists_oauth_to_v2_when_controller_is_compat(self):+ from config.v2_config import AgentsConfig, ClaudeConfig, RuntimeConfig, SlackConfig, V2Config++ controller = _StubController()+ service = AgentAuthService(controller)+ context = MessageContext(user_id="U1", channel_id="C1")+ done_task = asyncio.create_task(asyncio.sleep(0))+ await done_task+ flow = AgentAuthFlow(+ flow_id="flow-claude-compat-persist",+ backend="claude",+ settings_key="C1",+ initiator_user_id="U1",+ context=context,+ process=None,+ reader_task=done_task,+ waiter_task=done_task,+ claude_client=SimpleNamespace(),+ )+ 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 tempfile.TemporaryDirectory() as home:+ with _temporary_vibe_home(Path(home)):+ V2Config(+ mode="self_host",+ version="v2",+ slack=SlackConfig(),+ runtime=RuntimeConfig(default_cwd="/tmp/work"),+ agents=AgentsConfig(+ claude=ClaudeConfig(+ auth_mode="oauth",+ auth_mode_set=False,+ )+ ),+ ).save()+ controller.config = SimpleNamespace(+ language="en",+ claude=SimpleNamespace(auth_mode="oauth", auth_mode_set=False),+ )+ with patch("vibe.claude_config.apply_claude_auth"):+ await service._wait_for_claude_completion(flow)++ saved = V2Config.load()++ self.assertEqual(saved.agents.claude.auth_mode, "oauth")+ self.assertTrue(saved.agents.claude.auth_mode_set)+ self.assertTrue(controller.config.claude.auth_mode_set)+async def test_wait_for_claude_completion_reports_settings_cleanup_failure(self):controller = _StubController()service = AgentAuthService(controller)diff --git a/tests/test_claude_subprocess_env.py b/tests/test_claude_subprocess_env.pyindex f321ffa98..4d7f005a7 100644--- a/tests/test_claude_subprocess_env.py+++ b/tests/test_claude_subprocess_env.py@@ -16,7 +16,15 @@ from types import SimpleNamespaceimport pytest-from vibe.claude_config import build_claude_subprocess_env+from vibe.claude_config import (+ build_claude_subprocess_env,+ clear_claude_oauth_settings_backup,+ get_claude_oauth_settings_backup_path,+ read_claude_oauth_settings_backup,+ read_claude_settings_env,+ restore_claude_settings_env,+ write_claude_oauth_settings_backup,+)def _cfg(**kwargs) -> SimpleNamespace:@@ -48,6 +56,76 @@ def test_oauth_strips_inherited_api_key_and_auth_token() -> None:assert "PATH" not in out+def test_force_oauth_bypasses_api_key_mode_settings_and_config(+ tmp_path, monkeypatch+) -> None:+ claude_home = tmp_path / ".claude"+ claude_home.mkdir()+ (claude_home / "settings.json").write_text(+ '{"env":{"ANTHROPIC_API_KEY":"sk-settings","ANTHROPIC_AUTH_TOKEN":"bearer-settings","ANTHROPIC_BASE_URL":"https://settings.example"}}',+ encoding="utf-8",+ )+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(claude_home))++ env = {+ "ANTHROPIC_API_KEY": "sk-shell",+ "ANTHROPIC_AUTH_TOKEN": "bearer-shell",+ "ANTHROPIC_BASE_URL": "https://shell.example",+ "CLAUDE_CONFIG_DIR": str(claude_home),+ }++ out = build_claude_subprocess_env(+ _cfg(+ auth_mode="api_key",+ auth_mode_set=True,+ api_key="sk-configured",+ base_url="https://configured.example",+ ),+ base_env=env,+ force_oauth=True,+ )++ assert "ANTHROPIC_API_KEY" not in out+ assert "ANTHROPIC_AUTH_TOKEN" not in out+ assert "ANTHROPIC_BASE_URL" not in out+ assert out["CLAUDE_CONFIG_DIR"] == str(claude_home)+++def test_restore_claude_settings_env_preserves_base_url_only(tmp_path, monkeypatch) -> None:+ _empty_claude_home(tmp_path, monkeypatch)++ restore_claude_settings_env({"ANTHROPIC_BASE_URL": "https://relay.example"})++ assert read_claude_settings_env() == {+ "ANTHROPIC_BASE_URL": "https://relay.example",+ }+++def test_claude_oauth_settings_backup_round_trips_relevant_env_only(+ tmp_path, monkeypatch+) -> None:+ _empty_claude_home(tmp_path, monkeypatch)++ write_claude_oauth_settings_backup(+ {+ "ANTHROPIC_API_KEY": " sk-old ",+ "ANTHROPIC_BASE_URL": "https://relay.example",+ "UNRELATED": "ignored",+ }+ )++ assert read_claude_oauth_settings_backup() == {+ "ANTHROPIC_API_KEY": "sk-old",+ "ANTHROPIC_BASE_URL": "https://relay.example",+ }+ assert get_claude_oauth_settings_backup_path().exists()++ clear_claude_oauth_settings_backup()++ assert read_claude_oauth_settings_backup() is None+ assert not get_claude_oauth_settings_backup_path().exists()++def test_api_key_mode_injects_configured_key_and_drops_bearer(tmp_path, monkeypatch) -> None:_empty_claude_home(tmp_path, monkeypatch)env = {diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.pyindex 84216dc7b..bab07629a 100644--- a/tests/test_web_oauth_flow.py+++ b/tests/test_web_oauth_flow.py@@ -11,13 +11,25 @@ into ``_web_flows`` and mocking ``_send_claude_callback``.from __future__ import annotationsimport asyncio+import contextlibimport os+from pathlib import Pathfrom unittest.mock import AsyncMockimport pytest-from core.agent_auth_service import AgentAuthService, WebAuthFlow+from core.agent_auth_service import (+ AgentAuthService,+ ClaudeOAuthAttempt,+ ClaudeOAuthBatch,+ WebAuthFlow,+)from modules.agents.opencode.message_processor import extract_opencode_response_text+from vibe.claude_config import (+ read_claude_oauth_settings_backup,+ read_claude_settings_env,+ restore_claude_settings_env,+)class _Backend:@@ -44,6 +56,13 @@ class _StubController:config = _Config()[email protected](autouse=True)+def isolated_claude_config_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ claude_home = tmp_path / "default-claude"+ claude_home.mkdir()+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(claude_home))++@pytest.fixturedef service() -> AgentAuthService:return AgentAuthService(_StubController())@@ -53,6 +72,17 @@ def _run(coro):return asyncio.get_event_loop_policy().new_event_loop().run_until_complete(coro)+async def _start_opencode_flow_without_waiter(+ service: AgentAuthService, provider_id: str+) -> WebAuthFlow:+ flow = await service.start_web_setup("opencode", provider_id=provider_id)+ if flow.waiter_task is not None:+ flow.waiter_task.cancel()+ with contextlib.suppress(asyncio.CancelledError):+ await flow.waiter_task+ return flow++def test_opencode_message_text_extractor_ignores_non_text_by_default() -> None:message = {"parts": [@@ -227,32 +257,198 @@ def test_post_web_success_hook_swallows_exceptions(_run(service._invoke_post_web_success_hook("claude"))-def test_claude_oauth_settings_cleanup_failure_fails_web_flow(+def test_claude_oauth_settings_cleanup_failure_fails_web_start(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")+ service._create_claude_control_client = AsyncMock()monkeypatch.setattr("vibe.claude_config.apply_claude_auth", fail_cleanup)- _run(service._wait_for_claude_completion_web(flow))+ flow = _run(service.start_web_setup("claude"))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)+ service._create_claude_control_client.assert_not_awaited()+++def test_claude_web_oauth_failures_restore_settings_after_batch_finishes(+ service: AgentAuthService,+) -> None:+ backup = {"ANTHROPIC_API_KEY": "sk-old", "ANTHROPIC_BASE_URL": "https://old.example"}+ service._temporarily_clear_claude_settings_env_for_oauth = AsyncMock(+ side_effect=[backup, None],+ )+ service._restore_claude_settings_env_after_oauth_failure = AsyncMock()++ first_attempt = _run(service._begin_claude_oauth_attempt())+ second_attempt = _run(service._begin_claude_oauth_attempt())++ _run(service._finish_claude_oauth_attempt(first_attempt, succeeded=False))+ service._restore_claude_settings_env_after_oauth_failure.assert_not_awaited()++ _run(service._finish_claude_oauth_attempt(second_attempt, succeeded=False))+ service._restore_claude_settings_env_after_oauth_failure.assert_awaited_once_with(backup)+ assert first_attempt.settings_backup is None+ assert second_attempt.settings_backup is None+++def test_stale_claude_web_oauth_failure_ignores_backup_after_newer_success(+ service: AgentAuthService,+) -> None:+ stale_backup = {"ANTHROPIC_API_KEY": "sk-old", "ANTHROPIC_BASE_URL": "https://old.example"}+ service._temporarily_clear_claude_settings_env_for_oauth = AsyncMock(+ side_effect=[stale_backup, None],+ )+ service._restore_claude_settings_env_after_oauth_failure = AsyncMock()++ stale_attempt = _run(service._begin_claude_oauth_attempt())+ newer_attempt = _run(service._begin_claude_oauth_attempt())++ _run(service._finish_claude_oauth_attempt(newer_attempt, succeeded=True))+ _run(service._finish_claude_oauth_attempt(stale_attempt, succeeded=False))++ service._restore_claude_settings_env_after_oauth_failure.assert_not_awaited()+ assert stale_attempt.settings_backup is None+ assert newer_attempt.settings_backup is None+++def test_claude_oauth_new_batch_restores_after_previous_batch_success(+ service: AgentAuthService,+) -> None:+ first_backup = {"ANTHROPIC_API_KEY": "sk-old"}+ second_backup = {"ANTHROPIC_API_KEY": "sk-second"}+ service._temporarily_clear_claude_settings_env_for_oauth = AsyncMock(+ side_effect=[first_backup, None, second_backup],+ )+ service._restore_claude_settings_env_after_oauth_failure = AsyncMock()++ stale_attempt = _run(service._begin_claude_oauth_attempt())+ winning_attempt = _run(service._begin_claude_oauth_attempt())+ _run(service._finish_claude_oauth_attempt(winning_attempt, succeeded=True))+ _run(service._finish_claude_oauth_attempt(stale_attempt, succeeded=False))++ next_attempt = _run(service._begin_claude_oauth_attempt())+ _run(service._finish_claude_oauth_attempt(next_attempt, succeeded=False))++ service._restore_claude_settings_env_after_oauth_failure.assert_awaited_once_with(+ second_backup+ )+++def test_claude_oauth_begin_persists_backup_before_clearing_settings(+ service: AgentAuthService,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ claude_home = tmp_path / ".claude"+ claude_home.mkdir()+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(claude_home))+ backup = {+ "ANTHROPIC_API_KEY": "sk-old",+ "ANTHROPIC_BASE_URL": "https://relay.example",+ }+ restore_claude_settings_env(backup)++ attempt = _run(service._begin_claude_oauth_attempt())++ assert attempt.settings_backup == backup+ assert read_claude_settings_env() == {}+ assert read_claude_oauth_settings_backup() == backup+++def test_claude_oauth_restarts_restore_interrupted_durable_backup(+ service: AgentAuthService,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ claude_home = tmp_path / ".claude"+ claude_home.mkdir()+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(claude_home))+ backup = {+ "ANTHROPIC_API_KEY": "sk-old",+ "ANTHROPIC_BASE_URL": "https://relay.example",+ }+ restore_claude_settings_env(backup)++ _run(service._begin_claude_oauth_attempt())+ assert read_claude_settings_env() == {}++ AgentAuthService(_StubController())++ assert read_claude_settings_env() == backup+ assert read_claude_oauth_settings_backup() is None+++def test_claude_oauth_restarts_restore_pending_backup_even_when_config_is_oauth(+ service: AgentAuthService,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from vibe.claude_config import write_claude_oauth_settings_backup++ claude_home = tmp_path / ".claude"+ claude_home.mkdir()+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(claude_home))+ monkeypatch.setattr(_Backend, "auth_mode", "oauth", raising=False)+ monkeypatch.setattr(_Backend, "auth_mode_set", True, raising=False)+ backup = {+ "ANTHROPIC_API_KEY": "sk-old",+ "ANTHROPIC_BASE_URL": "https://relay.example",+ }+ write_claude_oauth_settings_backup(backup)++ service._recover_interrupted_claude_oauth_settings_backup()++ assert read_claude_settings_env() == backup+ assert read_claude_oauth_settings_backup() is None+++def test_claude_oauth_rollback_serializes_before_retry(+ service: AgentAuthService,+) -> None:+ first_backup = {"ANTHROPIC_API_KEY": "sk-old"}+ retry_backup = {"ANTHROPIC_API_KEY": "sk-retry"}+ service._temporarily_clear_claude_settings_env_for_oauth = AsyncMock(+ side_effect=[first_backup, retry_backup],+ )+ service._clear_pending_claude_oauth_settings_backup = AsyncMock()+ restore_started = asyncio.Event()+ release_restore = asyncio.Event()+ order: list[str] = []++ async def restore(_backup):+ order.append("restore-start")+ restore_started.set()+ await release_restore.wait()+ order.append("restore-end")+ return True++ service._restore_claude_settings_env_after_oauth_failure = restore++ async def scenario():+ first_attempt = await service._begin_claude_oauth_attempt()+ finish_task = asyncio.create_task(+ service._finish_claude_oauth_attempt(first_attempt, succeeded=False)+ )+ await restore_started.wait()+ retry_task = asyncio.create_task(service._begin_claude_oauth_attempt())+ await asyncio.sleep(0)++ assert not retry_task.done()+ assert service._temporarily_clear_claude_settings_env_for_oauth.await_count == 1++ release_restore.set()+ retry_attempt = await retry_task+ await finish_task+ return retry_attempt++ retry_attempt = _run(scenario())++ assert order == ["restore-start", "restore-end"]+ assert retry_attempt.settings_backup == retry_backupdef test_post_web_success_hook_unset_is_safe(@@ -335,7 +531,7 @@ def test_start_web_setup_opencode_extracts_url_and_device_code(}monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))- flow = _run(service.start_web_setup("opencode", provider_id="openai"))+ flow = _run(_start_opencode_flow_without_waiter(service, "openai"))# Headless variant (index 1) wins because the resolver walks the# auth list in reverse — important for remote sessions where the@@ -366,7 +562,7 @@ def test_start_web_setup_opencode_github_copilot_passes_prompt_answer(}monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))- _run(service.start_web_setup("opencode", provider_id="github-copilot"))+ _run(_start_opencode_flow_without_waiter(service, "github-copilot"))assert fake.start_calls == [("github-copilot", 0, {"deploymentType": "github.com"}),@@ -387,7 +583,7 @@ def test_start_web_setup_opencode_url_only_flow_has_no_device_code(}monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))- flow = _run(service.start_web_setup("opencode", provider_id="gitlab"))+ flow = _run(_start_opencode_flow_without_waiter(service, "gitlab"))assert flow.state == "awaiting_code"assert flow.url is not Noneassert flow.device_code is None@@ -597,6 +793,134 @@ def test_test_web_auth_happy_path_returns_excerpt(assert isinstance(result["duration_ms"], int)+def test_verify_web_login_claude_forces_oauth_env(+ service: AgentAuthService, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """After Claude's OAuth waiter completes, the verification probe must+ ignore stale inherited Anthropic env vars or it can report "no login"+ against the wrong auth source.+ """++ captured: dict = {}+ claude_home = tmp_path / ".claude"+ claude_home.mkdir()+ (claude_home / "settings.json").write_text(+ '{"env":{"ANTHROPIC_API_KEY":"sk-settings","ANTHROPIC_BASE_URL":"https://settings-relay.example"}}',+ encoding="utf-8",+ )++ class _FakeProcess:+ returncode = 0++ async def communicate(self):+ return (b'{"loggedIn": true}', b"")++ async def _spawn(*_args, **kwargs):+ captured["env"] = kwargs.get("env") or {}+ return _FakeProcess()++ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-stale-shell")+ monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://stale-relay.example")+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(claude_home))+ monkeypatch.setattr(_Backend, "auth_mode", "api_key", raising=False)+ monkeypatch.setattr(_Backend, "auth_mode_set", True, raising=False)+ monkeypatch.setattr(_Backend, "api_key", "sk-configured", raising=False)+ monkeypatch.setattr(_Backend, "base_url", "https://configured-relay.example", raising=False)+ monkeypatch.setattr(asyncio, "create_subprocess_exec", _spawn)+ original_backup = {"ANTHROPIC_API_KEY": "sk-original"}+ attempt = ClaudeOAuthAttempt(+ attempt_id=1,+ batch=ClaudeOAuthBatch(backup=original_backup),+ )+ clear_calls: list[str] = []+ observed_backup_after_probe: list[dict[str, str] | None] = []++ async def clear_settings():+ clear_calls.append("called")+ return {"ANTHROPIC_API_KEY": "sk-restored-by-overlap"}++ original_verify_login = service._verify_login++ async def verify_login_with_existing_backup(flow):+ result = await original_verify_login(flow)+ observed_backup_after_probe.append(flow.claude_oauth_attempt.settings_backup)+ return result++ monkeypatch.setattr(service, "_verify_login", verify_login_with_existing_backup)+ monkeypatch.setattr(service, "_temporarily_clear_claude_settings_env_for_oauth", clear_settings)++ ok, detail = _run(+ service._verify_web_login(+ "claude",+ force_oauth=True,+ claude_oauth_attempt=attempt,+ )+ )++ assert ok is True+ assert detail == '{"loggedIn": true}'+ assert "ANTHROPIC_API_KEY" not in captured["env"]+ assert "ANTHROPIC_BASE_URL" not in captured["env"]+ assert clear_calls == ["called"]+ assert observed_backup_after_probe == [original_backup]+ assert attempt.settings_backup == original_backup+++def test_test_web_auth_claude_oauth_env_removes_stale_anthropic_vars(+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The Settings Test button runs a real Claude subprocess; when OAuth is+ explicitly selected it must use the same env cleanup as live sessions.+ """++ captured: dict = {}++ class _FakeProcess:+ returncode = 0++ async def communicate(self):+ return (b"Hello from Claude", b"")++ async def _spawn(*_args, **kwargs):+ captured["env"] = kwargs.get("env") or {}+ return _FakeProcess()++ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-stale-shell")+ monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "bearer-stale-shell")+ monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://stale-relay.example")+ monkeypatch.setattr(_Backend, "auth_mode", "oauth", raising=False)+ monkeypatch.setattr(_Backend, "auth_mode_set", True, raising=False)+ monkeypatch.setattr(asyncio, "create_subprocess_exec", _spawn)++ result = _run(service.test_web_auth("claude"))++ assert result["ok"] is True+ assert "ANTHROPIC_API_KEY" not in captured["env"]+ assert "ANTHROPIC_AUTH_TOKEN" not in captured["env"]+ assert "ANTHROPIC_BASE_URL" not in captured["env"]+++def test_test_web_auth_claude_oauth_reports_settings_cleanup_failure(+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch+) -> None:+ async def _spawn(*_args, **_kwargs):+ raise AssertionError("Claude probe must not spawn when cleanup fails")++ def fail_cleanup(**_kwargs):+ raise OSError("settings locked")++ monkeypatch.setattr(_Backend, "auth_mode", "oauth", raising=False)+ monkeypatch.setattr(_Backend, "auth_mode_set", True, raising=False)+ monkeypatch.setattr("vibe.claude_config.apply_claude_auth", fail_cleanup)+ monkeypatch.setattr(asyncio, "create_subprocess_exec", _spawn)++ result = _run(service.test_web_auth("claude"))++ assert result["ok"] is False+ assert result["error"] == "settings_cleanup_failed"+ assert "Failed to clear Claude Code settings env" in result["detail"]++def test_test_web_auth_failure_surfaces_stderr(service: AgentAuthService, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/ui/src/App.tsx b/ui/src/App.tsxindex 3165890c1..2e26b1cd4 100644--- a/ui/src/App.tsx+++ b/ui/src/App.tsx@@ -33,7 +33,7 @@ import { WorkbenchInboxProvider } from './context/WorkbenchInboxContext';import { WorkbenchProjectsProvider } from './context/WorkbenchProjectsContext';import { ComposerBridgeProvider } from './context/ComposerBridgeContext';import { AgentationToggle } from './components/AgentationToggle';-import { useEffect, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import type { ReactNode } from 'react';import { hasConfiguredPlatformCredentials } from './lib/platforms';import { useTranslation } from 'react-i18next';@@ -45,11 +45,13 @@ import { Button } from './components/ui/button';const LOGIN_CHECK_PATHS = new Set(['/admin/logs', '/admin/settings/diagnostics']);const RemoteLoginRedirect = ({ target }: { target: string }) => {+ const { t } = useTranslation();+useEffect(() => {window.location.assign(target);}, [target]);- return <div className="min-h-screen flex items-center justify-center bg-bg text-text">Loading...</div>;+ return <div className="min-h-screen flex items-center justify-center bg-bg text-text">{t('common.loading')}</div>;};// Server error codes (from the Web UI's enforce_remote_access_cookie guard)@@ -154,6 +156,7 @@ const WebPushNotificationNavigator = () => {// page reload because ``<AppShell>`` got unmounted and re-mounted.const AuthGuard = ({ children }: { children: ReactNode }) => {const { getConfig, getAuthSession } = useApi();+ const { t } = useTranslation();const location = useLocation();const guardTarget = location.pathname + location.search;const [guardStatus, setGuardStatus] = useState<GuardStatus>('loading');@@ -165,6 +168,11 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {// `needs-setup` status refreshes to `ready` instead of bouncing the// user straight back to /setup.const isSetupRoute = location.pathname === '/setup';+ const previousIsSetupRouteRef = useRef(isSetupRoute);++ useEffect(() => {+ previousIsSetupRouteRef.current = isSetupRoute;+ }, [isSetupRoute]);useEffect(() => {let cancelled = false;@@ -231,7 +239,7 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {if (bypassSetupGuard) return children;if (guardStatus === 'loading') {- return <div className="min-h-screen flex items-center justify-center bg-bg text-text">Loading...</div>;+ return <div className="min-h-screen flex items-center justify-center bg-bg text-text">{t('common.loading')}</div>;}if (guardStatus === 'remote-login-required') {return <RemoteLoginRedirect target={guardTarget} />;@@ -241,6 +249,14 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {}if (guardStatus === 'needs-setup') {if (location.pathname === '/setup') return children;+ // A wizard finish navigates from /setup to / before the re-validation+ // effect can flip `guardStatus` to loading. Without this render-time+ // bridge, the stale setup-required state immediately redirects back to+ // /setup, so the first finish appears to "not take" even though the+ // config was already saved with setup_completed=true.+ if (previousIsSetupRouteRef.current) {+ return <div className="min-h-screen flex items-center justify-center bg-bg text-text">{t('common.loading')}</div>;+ }return <Navigate to="/setup" replace />;}return children;diff --git a/vibe/claude_config.py b/vibe/claude_config.pyindex 09d62ab6f..24230528c 100644--- a/vibe/claude_config.py+++ b/vibe/claude_config.py@@ -39,6 +39,7 @@ RELEVANT_ENV_KEYS = ("ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL",)+OAUTH_SETTINGS_ENV_BACKUP_NAME = ".avibe-oauth-settings-env-backup.json"def get_claude_home(home: Path | None = None) -> Path:@@ -74,6 +75,11 @@ def get_claude_credentials_path(home: Path | None = None) -> Path:return get_claude_home(home) / "credentials.json"+def get_claude_oauth_settings_backup_path(home: Path | None = None) -> Path:+ """Return Avibe's durable rollback file for Claude OAuth setup."""+ return get_claude_home(home) / OAUTH_SETTINGS_ENV_BACKUP_NAME++def read_claude_oauth_signed_in(home: Path | None = None) -> bool:"""Best-effort probe for whether Claude has a usable OAuth session.@@ -153,6 +159,69 @@ def _atomic_write(path: Path, content: str, *, mode: int = 0o600) -> None:logger.debug("chmod %s failed: %s", path, exc)+def _clean_relevant_env_values(env_values: Dict[str, str]) -> Dict[str, str]:+ out: Dict[str, str] = {}+ for key in RELEVANT_ENV_KEYS:+ raw = env_values.get(key)+ if isinstance(raw, str) and raw.strip():+ out[key] = raw.strip()+ return out+++def write_claude_oauth_settings_backup(+ env_values: Dict[str, str], home: Path | None = None+) -> None:+ """Persist a rollback copy of Claude settings env before OAuth cleanup.++ OAuth setup has to remove API-key/base-url overrides from Claude Code's+ ``settings.json`` before launching the OAuth control client. The rollback+ state must survive an Avibe process restart, so it lives next to Claude's+ settings file and uses the same private-file permissions.+ """+ cleaned = _clean_relevant_env_values(env_values)+ if not cleaned:+ clear_claude_oauth_settings_backup(home)+ return+ payload = {"version": 1, "env": cleaned}+ _atomic_write(+ get_claude_oauth_settings_backup_path(home),+ json.dumps(payload, indent=2) + "\n",+ mode=0o600,+ )+++def read_claude_oauth_settings_backup(+ home: Path | None = None,+) -> Dict[str, str] | None:+ """Read Avibe's pending Claude OAuth rollback backup, if present."""+ path = get_claude_oauth_settings_backup_path(home)+ if not path.exists():+ return None+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as exc:+ logger.warning("Claude OAuth settings backup read failed (%s)", exc)+ return None+ if not isinstance(data, dict):+ return None+ env_values = data.get("env")+ if not isinstance(env_values, dict):+ return None+ cleaned = _clean_relevant_env_values(env_values)+ return cleaned or None+++def clear_claude_oauth_settings_backup(home: Path | None = None) -> None:+ """Remove Avibe's pending Claude OAuth rollback backup."""+ path = get_claude_oauth_settings_backup_path(home)+ try:+ path.unlink()+ except FileNotFoundError:+ return+ except OSError as exc: # pragma: no cover - best effort cleanup+ logger.warning("Claude OAuth settings backup cleanup failed (%s)", exc)++def apply_claude_auth(*,auth_mode: str,@@ -220,6 +289,33 @@ def read_claude_settings_env(home: Path | None = None) -> Dict[str, str]:return out+def restore_claude_settings_env(env_values: Dict[str, str], home: Path | None = None) -> None:+ """Restore Anthropic-relevant Claude settings env values exactly.++ OAuth setup temporarily removes these keys so Claude Code cannot route+ the OAuth handshake through stale API-key settings. If that setup does+ not complete, the caller needs to put the previous settings back without+ changing header semantics or dropping a base-url-only relay setting.+ """+ path = get_claude_settings_path(home)+ settings = _load_settings_for_write(path)+ env_block = settings.setdefault("env", {})+ if not isinstance(env_block, dict):+ env_block = {}+ settings["env"] = env_block++ for key in RELEVANT_ENV_KEYS:+ env_block.pop(key, None)+ raw = env_values.get(key)+ if isinstance(raw, str) and raw.strip():+ env_block[key] = raw.strip()++ if not env_block:+ settings.pop("env", None)++ _atomic_write(path, json.dumps(settings, indent=2) + "\n", mode=0o600)++def read_claude_auth_state(home: Path | None = None) -> Dict[str, Any]:"""Return the user-visible Claude auth state for the Settings UI.@@ -321,7 +417,10 @@ def build_claude_subprocess_env(if claude_cfg is None and not force_oauth:return claude_env- auth_mode = getattr(claude_cfg, "auth_mode", "oauth") if claude_cfg is not None else "oauth"+ configured_auth_mode = (+ getattr(claude_cfg, "auth_mode", "oauth") if claude_cfg is not None else "oauth"+ )+ auth_mode = "oauth" if force_oauth else configured_auth_modeconfigured_key_raw = (getattr(claude_cfg, "api_key", None) or "").strip() if claude_cfg is not None else ""configured_base = (getattr(claude_cfg, "base_url", None) or "").strip() if claude_cfg is not None else ""settings_env = read_claude_settings_env()