diff --git a/agent_core/core/impl/llm/interface.py b/agent_core/core/impl/llm/interface.py index 670fa630..77249329 100644 --- a/agent_core/core/impl/llm/interface.py +++ b/agent_core/core/impl/llm/interface.py @@ -208,6 +208,19 @@ def _generic_empty_response_detail(provider: str, model: str) -> str: ) +def _subscription_connected(provider: Optional[str]) -> bool: + """Whether a ChatGPT, SuperGrok or Claude subscription is connected for + ``provider``. The factory prefers it over an API key.""" + if not provider: + return False + try: + from craftos_integrations.llm_oauth.tokens import has_credential + + return has_credential(provider) + except Exception: + return False + + class LLMInterface: """LLM interface with multi-provider support and hook-based customization. @@ -257,6 +270,7 @@ def __init__( # whether a Settings save actually changed anything. self._init_api_key = api_key self._init_base_url = base_url + self._init_subscription = False # Hooks for runtime-specific behavior self._get_token_count = get_token_count or (lambda: 0) @@ -332,6 +346,7 @@ def __init__( # OpenAI, which translates chat.completions calls to the Responses # API on the fly — no behavioral difference at the call sites. self._auth_mode: str = ctx.get("auth_mode", "api_key") + self._init_subscription = _subscription_connected(self.provider) if self.provider == "openai" and self._auth_mode == "subscription": logger.info( "[LLM] OpenAI ChatGPT subscription mode active — routing via" @@ -456,12 +471,16 @@ def reinitialize( old_api_key = self._init_api_key old_base_url = self._init_base_url provider_unchanged = target_provider == old_provider + # Connecting or disconnecting a subscription changes the client the + # factory builds even though the settings above stay the same. + target_subscription = _subscription_connected(target_provider) nothing_changed = ( provider_unchanged and target_model is not None and target_model == old_model and target_api_key == old_api_key and target_base_url == old_base_url + and target_subscription == self._init_subscription ) if nothing_changed: @@ -546,6 +565,7 @@ def reinitialize( # can tell whether anything actually changed. self._init_api_key = target_api_key self._init_base_url = target_base_url + self._init_subscription = target_subscription logger.info( f"[LLM] Reinitialized successfully with provider: {self.provider}, model: {self.model}" @@ -1015,9 +1035,22 @@ def _output_reservation(self, reasoning: Optional[ReasoningDecision]) -> int: count against it), so the window check reserves that cap; otherwise the provider would reject the request for size instead. """ - if reasoning is None: - return self.max_tokens - return reasoning.output_cap(self.max_tokens) + output_cap = ( + self.max_tokens + if reasoning is None + else reasoning.output_cap(self.max_tokens) + ) + # The Chat Completions transport applies the provider's ceiling + # after reasoning raises the cap. Reserve the value actually sent, + # or a small-window provider such as Qwen can reject every prompt. + profile = _get_registry().get(self.provider) + if ( + profile is not None + and profile.wire == "chat_completions" + and profile.max_output_tokens + ): + output_cap = min(output_cap, profile.max_output_tokens) + return output_cap def _generate_response_sync( self, diff --git a/agent_core/core/models/claude_code_client.py b/agent_core/core/models/claude_code_client.py new file mode 100644 index 00000000..298414ab --- /dev/null +++ b/agent_core/core/models/claude_code_client.py @@ -0,0 +1,167 @@ +"""Messages-compatible facade over Claude Code's documented print mode. + +CraftBot owns the agent loop. The CLI supplies inference only, with its +tools, MCP servers, hooks and session persistence disabled. Each call sends +the complete conversation as a labelled transcript in one user message; +image blocks remain native image input. Claude Code owns authentication. +""" + +from __future__ import annotations + +import json +import subprocess +import tempfile +from pathlib import Path +from types import SimpleNamespace + +from agent_core.core.models.reasoning import reasoning_options +from craftos_integrations.llm_oauth import claude_code + + +def _content(messages: list[dict]) -> list[dict]: + blocks = [] + if len(messages) > 1: + blocks.append( + { + "type": "text", + "text": "Continue this conversation by replying to its final user message.", + } + ) + for message in messages: + if len(messages) > 1: + blocks.append({"type": "text", "text": f"\n[{message['role']}]\n"}) + content = message.get("content", "") + if isinstance(content, str): + blocks.append({"type": "text", "text": content}) + continue + for block in content: + if block.get("type") in ("thinking", "redacted_thinking"): + continue + if block.get("type") not in ("text", "image"): + raise ValueError( + "Claude Code inference supports text and image messages only." + ) + blocks.append({k: v for k, v in block.items() if k != "cache_control"}) + return blocks + + +class ClaudeCodeClient: + def __init__(self, *, timeout: float = 600): + self.timeout = timeout + self.messages = self + + def create( + self, + *, + model: str, + messages: list[dict], + system=None, + max_tokens: int = 16384, + thinking=None, + output_config=None, + extra_body=None, + ): + if not claude_code.has_credential(): + raise RuntimeError( + "Claude subscription disconnected. Reconnect in Settings or save an API key." + ) + if isinstance(system, list): + system = "\n\n".join(block.get("text", "") for block in system) + payload = { + "type": "user", + "message": {"role": "user", "content": _content(messages)}, + } + env = {"CLAUDE_CODE_MAX_OUTPUT_TOKENS": str(max_tokens)} + # The Messages API omits thinking for Off on Claude 4.x; the CLI + # enables it by default. Use the same model rules as the transport + # so models whose provider default includes thinking keep it. + options = reasoning_options("anthropic", model, "subscription") + omitted_means_off = ( + thinking is None + and options is not None + and options.provider_default == "off" + ) + if omitted_means_off or (thinking and thinking.get("type") == "disabled"): + env["MAX_THINKING_TOKENS"] = "0" + elif thinking and thinking.get("budget_tokens") is not None: + env["MAX_THINKING_TOKENS"] = str(thinking["budget_tokens"]) + + # File + stdin inputs avoid OS command-line limits and shell escaping, + # even with large system prompts or base64 screenshots on Windows. + with tempfile.TemporaryDirectory(prefix="craftbot-claude-") as directory: + root = Path(directory) + prompt = root / "system.txt" + prompt.write_text( + system or "You are a helpful assistant.", encoding="utf-8" + ) + settings = root / "settings.json" + settings.write_text('{"disableAllHooks":true}', encoding="utf-8") + mcp = root / "mcp.json" + mcp.write_text('{"mcpServers":{}}', encoding="utf-8") + args = [ + "--print", + "--input-format", + "stream-json", + "--output-format", + "stream-json", + "--verbose", + "--model", + model, + "--max-turns", + "1", + "--tools", + "", + "--strict-mcp-config", + "--mcp-config", + str(mcp), + "--setting-sources", + "", + "--settings", + str(settings), + "--no-session-persistence", + "--disable-slash-commands", + "--system-prompt-file", + str(prompt), + ] + effort = (output_config or {}).get("effort") + if effort: + args.extend(["--effort", effort]) + try: + result = claude_code.run_cli( + args, + input=json.dumps(payload) + "\n", + cwd=directory, + env_overrides=env, + timeout=self.timeout, + ) + except subprocess.TimeoutExpired as exc: + raise RuntimeError("Claude Code inference timed out.") from exc + + final = None + for line in result.stdout.splitlines(): + try: + event = json.loads(line) + except ValueError: + continue + if isinstance(event, dict) and event.get("type") == "result": + final = event + if final is None: + raise RuntimeError( + "Claude Code did not return a result. Update the CLI and reconnect " + "in Settings using CraftBot's separate Claude profile." + ) + if result.returncode or final.get("is_error"): + detail = final.get("result") or "; ".join(final.get("errors") or []) + raise RuntimeError( + f"Claude Code inference failed: {detail or final.get('subtype', 'unknown error')}" + ) + usage = final.get("usage") or {} + return SimpleNamespace( + content=[SimpleNamespace(type="text", text=final.get("result") or "")], + usage=SimpleNamespace( + input_tokens=usage.get("input_tokens", 0), + output_tokens=usage.get("output_tokens", 0), + cache_creation_input_tokens=usage.get("cache_creation_input_tokens", 0), + cache_read_input_tokens=usage.get("cache_read_input_tokens", 0), + ), + ) diff --git a/agent_core/core/models/connection_tester.py b/agent_core/core/models/connection_tester.py index 1b911467..c306fcc3 100644 --- a/agent_core/core/models/connection_tester.py +++ b/agent_core/core/models/connection_tester.py @@ -74,6 +74,21 @@ def _test_provider_connection_inner( if provider == "openai": return _test_openai(api_key, timeout, model) elif provider == "anthropic": + from craftos_integrations.llm_oauth import claude_code + + if claude_code.has_credential(): + from agent_core.core.models.claude_code_client import ClaudeCodeClient + + ClaudeCodeClient(timeout=timeout).messages.create( + model=model or cfg.connection_test_model, + max_tokens=32, + messages=[{"role": "user", "content": "Reply with OK."}], + ) + return { + "success": True, + "provider": provider, + "message": "Claude Code subscription connection successful.", + } return _test_anthropic(api_key, timeout, model) elif provider == "gemini": return _test_gemini(api_key, timeout, model) diff --git a/agent_core/core/models/factory.py b/agent_core/core/models/factory.py index 7d8162f8..bed51d34 100644 --- a/agent_core/core/models/factory.py +++ b/agent_core/core/models/factory.py @@ -432,6 +432,22 @@ def create( } if provider == "anthropic": + try: + from craftos_integrations.llm_oauth.tokens import has_credential + + claude_code_connected = has_credential(provider) + except ImportError: + claude_code_connected = False + + if claude_code_connected: + from agent_core.core.models.claude_code_client import ClaudeCodeClient + + return { + **empty_context, + "anthropic_client": ClaudeCodeClient(), + "initialized": True, + "auth_mode": "subscription", + } if not api_key: if deferred: return empty_context diff --git a/agent_core/core/models/provider_config.py b/agent_core/core/models/provider_config.py index 2be66cff..3a0d13b2 100644 --- a/agent_core/core/models/provider_config.py +++ b/agent_core/core/models/provider_config.py @@ -238,6 +238,8 @@ def resolve_temperature(profile: Optional[ProviderProfile], caller_temperature): display_name="Anthropic", wire="anthropic_messages", settings_key="anthropic", + oauth_backend="claude_code", + subscription_label="Sign in with Claude", connection_test_model="claude-haiku-4-5-20251001", connection_test_max_tokens=1, default_models={ diff --git a/app/agent_app/test_data_safety.py b/app/agent_app/test_data_safety.py index 2492fa9e..0675c1f7 100644 --- a/app/agent_app/test_data_safety.py +++ b/app/agent_app/test_data_safety.py @@ -1742,14 +1742,15 @@ async def _fake_run(cmd, timeout, cwd=None): # with "-" was parsed as a flag: nothing saved, launch "succeeded", and every # CLI read ran unauthenticated (IP Manager, 2026-09-29). The save is now # confirmed from the database, and the password always follows `--`. -import sqlite3 as _sqlite3 - with tempfile.TemporaryDirectory() as tmp: runner23b = AgentAppRunner(Path(tmp)) proj23b = Path(tmp) / "proj" (proj23b / "pb" / "pb_data").mkdir(parents=True) (proj23b / ".superuser").write_text( - _json.dumps({"email": "agent@agent-app.local", "password": "-Starts-with-a-dash"}) + "\n", + _json.dumps( + {"email": "agent@agent-app.local", "password": "-Starts-with-a-dash"} + ) + + "\n", encoding="utf-8", ) seen_cmds = [] @@ -1768,7 +1769,9 @@ async def _silent_fail(cmd, timeout, cwd=None): raise AssertionError("an upsert that saved nothing must refuse to serve") except RuntimeError as e: assert "refusing to serve" in str(e) - assert "-Starts-with-a-dash" not in str(e), "the password must never appear in the error" + assert "-Starts-with-a-dash" not in str(e), ( + "the password must never appear in the error" + ) cmd = seen_cmds[-1] sep = cmd.index("--") @@ -1777,10 +1780,13 @@ async def _silent_fail(cmd, timeout, cwd=None): async def _real_save(cmd, timeout, cwd=None): db = proj23b / "pb" / "pb_data" / "data.db" - con = _sqlite3.connect(db) + con = sqlite3.connect(db) con.execute("CREATE TABLE IF NOT EXISTS _superusers (email TEXT, updated TEXT)") con.execute("DELETE FROM _superusers") - con.execute("INSERT INTO _superusers VALUES (?, ?)", ("agent@agent-app.local", "2026-09-29 01:00:00.000Z")) + con.execute( + "INSERT INTO _superusers VALUES (?, ?)", + ("agent@agent-app.local", "2026-09-29 01:00:00.000Z"), + ) con.commit() con.close() return (0, 'Successfully saved superuser "agent@agent-app.local"!') diff --git a/app/config.py b/app/config.py index 756dbd70..2f0d8741 100644 --- a/app/config.py +++ b/app/config.py @@ -7,11 +7,11 @@ import json import os -import threading from pathlib import Path from typing import Any, Dict, Optional, Tuple from app import paths +from app.settings_store import settings_transaction, settings_write_lock, write_settings def get_project_root() -> Path: @@ -158,6 +158,7 @@ def _get_default_settings() -> Dict[str, Any]: } +@settings_transaction def get_settings(reload: bool = False) -> Dict[str, Any]: """Load and return settings from settings.json. @@ -518,7 +519,7 @@ def is_prewarm_all_drives_enabled() -> bool: # Serializes this module's read-modify-write of settings.json between threads # (the Mini Browser saves from its own thread). -_settings_write_lock = threading.Lock() +_settings_write_lock = settings_write_lock def _clean_mini_browser_value(key: str, value: Any) -> Tuple[bool, Any]: @@ -620,6 +621,7 @@ def get_slow_mode_tpm_limit() -> int: return settings.get("model", {}).get("slow_mode_tpm_limit", 30000) +@settings_transaction def save_settings(settings: Dict[str, Any]) -> None: """Save settings to settings.json. @@ -627,10 +629,8 @@ def save_settings(settings: Dict[str, Any]) -> None: settings: Dictionary with settings to save. """ global _settings_cache + write_settings(SETTINGS_CONFIG_PATH, settings) _settings_cache = settings - SETTINGS_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) - with open(SETTINGS_CONFIG_PATH, "w", encoding="utf-8") as f: - json.dump(settings, f, indent=2, ensure_ascii=False) def get_os_language() -> str: @@ -660,13 +660,15 @@ def get_ui_language() -> str: return general.get("ui_language") or general.get("os_language", "en") +@settings_transaction def set_ui_language(lang_code: str) -> None: """Persist the browser UI language to settings.json ``general.ui_language``.""" - settings = get_settings() + settings = get_settings(reload=True) settings.setdefault("general", {})["ui_language"] = lang_code save_settings(settings) +@settings_transaction def detect_and_save_os_language() -> str: """Detect OS language and save to settings. Called on first launch only. @@ -682,7 +684,7 @@ def detect_and_save_os_language() -> str: lang_code = "en" # Save to settings.json - settings = get_settings() + settings = get_settings(reload=True) settings.setdefault("general", {})["os_language"] = lang_code save_settings(settings) return lang_code diff --git a/app/onboarding/interfaces/steps.py b/app/onboarding/interfaces/steps.py index 16c25388..7b21836a 100644 --- a/app/onboarding/interfaces/steps.py +++ b/app/onboarding/interfaces/steps.py @@ -234,9 +234,11 @@ def _subscription_connected(self) -> bool: if not self.supports_subscription_oauth(): return False try: - from app.ui_layer.settings.provider_settings import get_subscription_status + from craftos_integrations.llm_oauth.tokens import has_credential - return bool(get_subscription_status(self.provider).get("connected")) + # Validation only needs the saved opt-in, as does the factory. + # Live account checks run separately off the browser event loop. + return has_credential(self.provider) except Exception: return False diff --git a/app/settings_store.py b/app/settings_store.py new file mode 100644 index 00000000..9c5402a4 --- /dev/null +++ b/app/settings_store.py @@ -0,0 +1,57 @@ +"""Shared serialization and atomic writes for settings.json.""" + +from __future__ import annotations + +import json +import os +import tempfile +import threading +import time +from functools import wraps +from pathlib import Path + + +settings_write_lock = threading.RLock() + + +def settings_transaction(function): + """Serialize a settings read-modify-write, including nested mutations.""" + + @wraps(function) + def wrapped(*args, **kwargs): + with settings_write_lock: + return function(*args, **kwargs) + + return wrapped + + +def write_settings(path: Path, settings: dict) -> None: + """Publish a complete JSON snapshot without exposing a partial write. + + Mutators must hold settings_write_lock from their read through this write. + The reentrant lock also protects callers that only publish a snapshot. + """ + with settings_write_lock: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary = tempfile.mkstemp( + prefix=f".{path.name}.", dir=path.parent + ) + try: + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + json.dump(settings, stream, indent=2, ensure_ascii=False) + stream.flush() + os.fsync(stream.fileno()) + if path.exists(): + os.chmod(temporary, path.stat().st_mode) + for attempt in range(10): + try: + os.replace(temporary, path) + break + except PermissionError: + # A Windows reader can briefly deny replacement. + if os.name != "nt" or attempt == 9: + raise + time.sleep(0.005 * (attempt + 1)) + finally: + if os.path.exists(temporary): + os.unlink(temporary) diff --git a/app/ui_layer/adapters/browser_adapter.py b/app/ui_layer/adapters/browser_adapter.py index ab357d7f..230d0756 100644 --- a/app/ui_layer/adapters/browser_adapter.py +++ b/app/ui_layer/adapters/browser_adapter.py @@ -2935,7 +2935,7 @@ async def _handle_local_llm_pull_model( try: from app.ui_layer.settings.model_settings import get_model_settings - settings_data = get_model_settings() + settings_data = await asyncio.to_thread(get_model_settings) base_url = settings_data.get("base_urls", {}).get("remote") except Exception: pass @@ -6107,7 +6107,8 @@ async def _handle_model_providers_get(self) -> None: async def _handle_model_settings_get(self) -> None: """Get current model settings.""" try: - result = get_model_settings() + # Includes subscription status, which runs the Claude CLI. + result = await asyncio.to_thread(get_model_settings) await self._broadcast( { "type": "model_settings_get", @@ -6125,6 +6126,19 @@ async def _handle_model_settings_get(self) -> None: } ) + def _model_change_lock(self) -> asyncio.Lock: + """Order persistence, activation and rollbacks across all browser clients.""" + if not hasattr(self, "_model_settings_lock"): + self._model_settings_lock = asyncio.Lock() + return self._model_settings_lock + + def _subscription_request(self, provider: str) -> object: + if not hasattr(self, "_subscription_requests"): + self._subscription_requests = {} + request = object() + self._subscription_requests[provider] = request + return request + async def _handle_model_settings_update(self, data: Dict[str, Any]) -> None: """Update model settings. @@ -6216,127 +6230,155 @@ async def _handle_model_settings_update(self, data: Dict[str, Any]) -> None: ) return - # Capture the current image-gen provider/model BEFORE saving, so a - # failed reinitialize below can roll the persisted values back and - # keep settings.json consistent with the still-live interface. - prev_image_gen_provider = None - prev_image_gen_model = None - if image_gen_provider: - from app.config import ( - get_image_gen_provider as _get_ig_provider, - get_image_gen_model as _get_ig_model, - ) + async with self._model_change_lock(): + # Capture the current image-gen provider/model BEFORE saving, so a + # failed reinitialize below can roll the persisted values back and + # keep settings.json consistent with the still-live interface. + prev_image_gen_provider = None + prev_image_gen_model = None + if image_gen_provider: + from app.config import ( + get_image_gen_provider as _get_ig_provider, + get_image_gen_model as _get_ig_model, + ) + + prev_image_gen_provider = _get_ig_provider() + prev_image_gen_model = _get_ig_model() + + prev_video_gen_provider = None + prev_video_gen_model = None + if video_gen_provider: + from app.config import ( + get_video_gen_provider as _get_vg_provider, + get_video_gen_model as _get_vg_model, + ) - prev_image_gen_provider = _get_ig_provider() - prev_image_gen_model = _get_ig_model() + prev_video_gen_provider = _get_vg_provider() + prev_video_gen_model = _get_vg_model() - prev_video_gen_provider = None - prev_video_gen_model = None - if video_gen_provider: - from app.config import ( - get_video_gen_provider as _get_vg_provider, - get_video_gen_model as _get_vg_model, + # Step 3: Now save settings (validation and connection test passed) + result = await asyncio.to_thread( + update_model_settings, + include_subscription_status=False, + llm_provider=new_provider, + vlm_provider=vlm_provider, + image_gen_provider=image_gen_provider, + video_gen_provider=video_gen_provider, + llm_model=data.get("llmModel"), + vlm_model=data.get("vlmModel"), + image_gen_model=data.get("imageGenModel"), + video_gen_model=data.get("videoGenModel"), + api_key=api_key, + provider_for_key=provider_for_key, + base_url=base_url, + provider_for_url=data.get("providerForUrl"), + aws_credentials=data.get("awsCredentials"), ) - prev_video_gen_provider = _get_vg_provider() - prev_video_gen_model = _get_vg_model() - - # Step 3: Now save settings (validation and connection test passed) - result = update_model_settings( - llm_provider=new_provider, - vlm_provider=vlm_provider, - image_gen_provider=image_gen_provider, - video_gen_provider=video_gen_provider, - llm_model=data.get("llmModel"), - vlm_model=data.get("vlmModel"), - image_gen_model=data.get("imageGenModel"), - video_gen_model=data.get("videoGenModel"), - api_key=api_key, - provider_for_key=provider_for_key, - base_url=base_url, - provider_for_url=data.get("providerForUrl"), - aws_credentials=data.get("awsCredentials"), - ) + # Reinitialize LLM/VLM with new provider settings + if result.get("success") and new_provider: + try: + agent = self._controller.agent + agent.reinitialize_llm(new_provider) + logger.info( + f"[BROWSER] LLM reinitialized with provider: {new_provider}" + ) + except Exception as e: + logger.warning(f"[BROWSER] Failed to reinitialize LLM: {e}") + result["warning"] = ( + f"Settings saved but LLM reinitialization failed: {e}" + ) - # Reinitialize LLM/VLM with new provider settings - if result.get("success") and new_provider: - try: - agent = self._controller.agent - agent.reinitialize_llm(new_provider) - logger.info( - f"[BROWSER] LLM reinitialized with provider: {new_provider}" - ) - except Exception as e: - logger.warning(f"[BROWSER] Failed to reinitialize LLM: {e}") - result["warning"] = ( - f"Settings saved but LLM reinitialization failed: {e}" - ) + # Reinitialize image gen interface when its provider changes. + # Settings are already persisted above, and reinitialize_image_gen + # only swaps the live interface on success — so if it fails (e.g. + # the new provider has no API key) we must roll the saved image-gen + # provider/model back to match the still-live interface. Otherwise + # settings.json would advertise a provider the running interface + # can't serve. + if result.get("success") and image_gen_provider: + reinit_ok = False + try: + agent = self._controller.agent + reinit_ok = agent.reinitialize_image_gen(image_gen_provider) + except Exception as e: + logger.warning( + f"[BROWSER] Failed to reinitialize image gen: {e}" + ) - # Reinitialize image gen interface when its provider changes. - # Settings are already persisted above, and reinitialize_image_gen - # only swaps the live interface on success — so if it fails (e.g. - # the new provider has no API key) we must roll the saved image-gen - # provider/model back to match the still-live interface. Otherwise - # settings.json would advertise a provider the running interface - # can't serve. - if result.get("success") and image_gen_provider: - reinit_ok = False - try: - agent = self._controller.agent - reinit_ok = agent.reinitialize_image_gen(image_gen_provider) - except Exception as e: - logger.warning(f"[BROWSER] Failed to reinitialize image gen: {e}") + if reinit_ok: + logger.info( + f"[BROWSER] Image gen reinitialized with provider: {image_gen_provider}" + ) + else: + # Roll persisted image-gen settings back to the previous + # (still-live) values to avoid a settings/interface mismatch. + await asyncio.to_thread( + update_model_settings, + include_subscription_status=False, + image_gen_provider=prev_image_gen_provider, + image_gen_model=prev_image_gen_model, + ) + msg = ( + f"Image generation provider '{image_gen_provider}' could not be " + f"initialized — check its API key. Kept '{prev_image_gen_provider}'." + ) + logger.warning(f"[BROWSER] {msg}") + result["warning"] = result.get("warning") or msg - if reinit_ok: - logger.info( - f"[BROWSER] Image gen reinitialized with provider: {image_gen_provider}" - ) - else: - # Roll persisted image-gen settings back to the previous - # (still-live) values to avoid a settings/interface mismatch. - update_model_settings( - image_gen_provider=prev_image_gen_provider, - image_gen_model=prev_image_gen_model, - ) - msg = ( - f"Image generation provider '{image_gen_provider}' could not be " - f"initialized — check its API key. Kept '{prev_image_gen_provider}'." - ) - logger.warning(f"[BROWSER] {msg}") - result["warning"] = result.get("warning") or msg + # Reinitialize video gen interface when its provider changes. + # Mirrors the image gen pattern: roll back on reinit failure. + if result.get("success") and video_gen_provider: + reinit_vid_ok = False + try: + agent = self._controller.agent + reinit_vid_ok = agent.reinitialize_video_gen(video_gen_provider) + except Exception as e: + logger.warning( + f"[BROWSER] Failed to reinitialize video gen: {e}" + ) - # Reinitialize video gen interface when its provider changes. - # Mirrors the image gen pattern: roll back on reinit failure. - if result.get("success") and video_gen_provider: - reinit_vid_ok = False - try: - agent = self._controller.agent - reinit_vid_ok = agent.reinitialize_video_gen(video_gen_provider) - except Exception as e: - logger.warning(f"[BROWSER] Failed to reinitialize video gen: {e}") + if reinit_vid_ok: + logger.info( + f"[BROWSER] Video gen reinitialized with provider: {video_gen_provider}" + ) + else: + await asyncio.to_thread( + update_model_settings, + include_subscription_status=False, + video_gen_provider=prev_video_gen_provider, + video_gen_model=prev_video_gen_model, + ) + msg = ( + f"Video generation provider '{video_gen_provider}' could not be " + f"initialized — check its API key. Kept '{prev_video_gen_provider}'." + ) + logger.warning(f"[BROWSER] {msg}") + result["warning"] = result.get("warning") or msg - if reinit_vid_ok: - logger.info( - f"[BROWSER] Video gen reinitialized with provider: {video_gen_provider}" - ) - else: - update_model_settings( - video_gen_provider=prev_video_gen_provider, - video_gen_model=prev_video_gen_model, - ) - msg = ( - f"Video generation provider '{video_gen_provider}' could not be " - f"initialized — check its API key. Kept '{prev_video_gen_provider}'." + # Status may invoke a slow CLI. Persistence and live activation are + # already complete, so another Save can safely proceed meanwhile. + if result.get("success"): + current = await asyncio.to_thread(get_model_settings) + result["subscription_oauth"] = current.get("subscription_oauth", {}) + + async with self._model_change_lock(): + if result.get("success"): + # Another client may have saved while status was pending. + # Broadcast current saved values so a late response cannot + # move either client's selector back to an older provider. + current = await asyncio.to_thread( + get_model_settings, include_subscription_status=False ) - logger.warning(f"[BROWSER] {msg}") - result["warning"] = result.get("warning") or msg - - await self._broadcast( - { - "type": "model_settings_update", - "data": result, - } - ) + current.pop("subscription_oauth", None) + if current.get("success"): + result.update(current) + await self._broadcast( + { + "type": "model_settings_update", + "data": result, + } + ) except Exception as e: await self._broadcast( { @@ -6416,7 +6458,7 @@ async def _handle_ollama_models_get(self, base_url: Optional[str] = None) -> Non """Fetch available models from Ollama and broadcast to frontend.""" try: if not base_url: - settings_data = get_model_settings() + settings_data = await asyncio.to_thread(get_model_settings) base_url = settings_data.get("base_urls", {}).get("remote") result = await asyncio.to_thread(get_ollama_models, base_url=base_url) await self._broadcast({"type": "ollama_models_get", "data": result}) @@ -6569,10 +6611,14 @@ async def _handle_model_subscription_connect(self, provider: str) -> None: provider is echoed back in ``active_provider`` so the frontend dropdown updates immediately. """ + request = self._subscription_request(provider) try: success, message = await connect_subscription_async(provider) - active_provider = self._activate_provider_via_settings(success, provider) - status_payload = get_subscription_status(provider) + active_provider = await self._activate_provider_via_settings( + success, provider, request=request + ) + # Claude's status runs its CLI, so keep it off the event loop. + status_payload = await asyncio.to_thread(get_subscription_status, provider) await self._broadcast( { "type": "model_subscription_connect", @@ -6598,8 +6644,8 @@ async def _handle_model_subscription_connect(self, provider: str) -> None: } ) - def _activate_provider_via_settings( - self, connect_success: bool, provider: str + async def _activate_provider_via_settings( + self, connect_success: bool, provider: str, *, request: object = None ) -> Optional[str]: """Reuse the manual-Save path to make ``provider`` the active LLM. @@ -6614,10 +6660,22 @@ def _activate_provider_via_settings( if not connect_success: return None try: - update_model_settings(llm_provider=provider) - self._controller.agent.reinitialize_llm(provider) - logger.info(f"[BROWSER] LLM reinitialized with provider: {provider}") - return provider + async with self._model_change_lock(): + if ( + request is not None + and self._subscription_requests.get(provider) is not request + ): + return None + result = await asyncio.to_thread( + update_model_settings, + llm_provider=provider, + include_subscription_status=False, + ) + if not result.get("success"): + return None + self._controller.agent.reinitialize_llm(provider) + logger.info(f"[BROWSER] LLM reinitialized with provider: {provider}") + return provider except Exception as e: logger.warning( f"[BROWSER] Failed to activate provider {provider} after " @@ -6635,30 +6693,34 @@ async def _handle_model_subscription_disconnect(self, provider: str) -> None: the factory rebuilds the client — falling back to the stored API key now that the subscription credential is gone. """ + self._subscription_request(provider) try: - success, message = disconnect_subscription(provider) - warning = None - if success: - try: - from app.ui_layer.settings.provider_settings import ( - get_current_provider, - ) + async with self._model_change_lock(): + success, message = await asyncio.to_thread( + disconnect_subscription, provider + ) + warning = None + if success: + try: + from app.ui_layer.settings.provider_settings import ( + get_current_provider, + ) - if get_current_provider() == provider: - self._controller.agent.reinitialize_llm(provider) - logger.info( - f"[BROWSER] LLM reinitialized with provider {provider} " - "after subscription disconnect (API-key mode)" + if get_current_provider() == provider: + self._controller.agent.reinitialize_llm(provider) + logger.info( + f"[BROWSER] LLM reinitialized with provider {provider} " + "after subscription disconnect (API-key mode)" + ) + except Exception as e: + logger.warning( + f"[BROWSER] LLM reinit after {provider} subscription " + f"disconnect failed: {e}" + ) + warning = ( + "Subscription disconnected, but the model could not be " + f"reinitialized: {e}" ) - except Exception as e: - logger.warning( - f"[BROWSER] LLM reinit after {provider} subscription " - f"disconnect failed: {e}" - ) - warning = ( - "Subscription disconnected, but the model could not be " - f"reinitialized: {e}" - ) await self._broadcast( { "type": "model_subscription_disconnect", @@ -6667,7 +6729,9 @@ async def _handle_model_subscription_disconnect(self, provider: str) -> None: "provider": provider, "message": message, "warning": warning, - "status": get_subscription_status(provider), + "status": await asyncio.to_thread( + get_subscription_status, provider + ), }, } ) @@ -6687,7 +6751,7 @@ async def _handle_model_subscription_disconnect(self, provider: str) -> None: async def _handle_model_subscription_status(self, provider: str) -> None: """Return current connection status for a given provider.""" try: - status_payload = get_subscription_status(provider) + status_payload = await asyncio.to_thread(get_subscription_status, provider) await self._broadcast( { "type": "model_subscription_status", @@ -6750,11 +6814,14 @@ async def _handle_model_subscription_complete( ``_handle_model_subscription_connect`` does — see ``_activate_provider_via_settings``. """ + request = self._subscription_request(provider) try: success, message = await asyncio.to_thread( complete_subscription, provider, code, attempt_id ) - active_provider = self._activate_provider_via_settings(success, provider) + active_provider = await self._activate_provider_via_settings( + success, provider, request=request + ) await self._broadcast( { "type": "model_subscription_complete", @@ -6762,7 +6829,9 @@ async def _handle_model_subscription_complete( "success": success, "provider": provider, "message": message, - "status": get_subscription_status(provider), + "status": await asyncio.to_thread( + get_subscription_status, provider + ), "active_provider": active_provider, }, } diff --git a/app/ui_layer/browser/frontend/src/locales/en/onboarding.json b/app/ui_layer/browser/frontend/src/locales/en/onboarding.json index 183eb89f..620f00b3 100644 --- a/app/ui_layer/browser/frontend/src/locales/en/onboarding.json +++ b/app/ui_layer/browser/frontend/src/locales/en/onboarding.json @@ -57,6 +57,9 @@ "useOpenRouter": "Having connection issues? Use OpenRouter instead →" }, "sub": { + "recoveryHint": "This saved subscription is still selected. Disconnect it to use an API key, or sign in again.", + "claudeProfileNote": "Sign in separately for CraftBot. Disconnect signs out of this profile without affecting your standalone Claude Code login.", + "actionFailed": "Could not update the subscription connection. Please try again.", "working": "Working…", "pastePlaceholder": "Paste the code from the sign-in page", "submitting": "Submitting…", diff --git a/app/ui_layer/browser/frontend/src/locales/en/settings.json b/app/ui_layer/browser/frontend/src/locales/en/settings.json index c06e81ec..7617e256 100644 --- a/app/ui_layer/browser/frontend/src/locales/en/settings.json +++ b/app/ui_layer/browser/frontend/src/locales/en/settings.json @@ -144,6 +144,10 @@ "startingShort": "Starting..." }, "subscription": { + "recoveryHint": "This saved subscription is still selected. Disconnect it to use an API key, or sign in again.", + "claudeProfileNote": "Sign in separately for CraftBot. Disconnect signs out of this profile without affecting your standalone Claude Code login.", + "disconnectFailed": "Could not disconnect the subscription. Please try again.", + "connectFailed": "Could not sign in to the subscription. Please try again.", "label": "Subscription", "awaitingCode": "Awaiting code", "pastePlaceholder": "Paste the code from the sign-in page", diff --git a/app/ui_layer/browser/frontend/src/pages/Onboarding/OnboardingPage.module.css b/app/ui_layer/browser/frontend/src/pages/Onboarding/OnboardingPage.module.css index 08122947..3c058fee 100644 --- a/app/ui_layer/browser/frontend/src/pages/Onboarding/OnboardingPage.module.css +++ b/app/ui_layer/browser/frontend/src/pages/Onboarding/OnboardingPage.module.css @@ -177,6 +177,13 @@ flex-shrink: 0; } +.hint { + color: var(--text-secondary); + font-size: var(--text-sm); + line-height: var(--leading-normal); + margin: var(--space-3) 0; +} + /* Intro/welcome message - regular weight so only the key phrases (in ) stand out; two lines with a gap before the "Now, before we begin…" kicker. */ .introMessage { diff --git a/app/ui_layer/browser/frontend/src/pages/Onboarding/OnboardingPage.tsx b/app/ui_layer/browser/frontend/src/pages/Onboarding/OnboardingPage.tsx index 75af727a..bb6e2cfe 100644 --- a/app/ui_layer/browser/frontend/src/pages/Onboarding/OnboardingPage.tsx +++ b/app/ui_layer/browser/frontend/src/pages/Onboarding/OnboardingPage.tsx @@ -15,6 +15,7 @@ import { import { Button } from '../../components/ui' import { useTranslation, Trans } from 'react-i18next' import { useWebSocket } from '../../contexts/WebSocketContext' +import { useToast } from '../../contexts/ToastContext' import { useAppDispatch, useAppSelector } from '../../store/hooks' import { getSocketClient } from '../../store/socket/socketInstance' import { @@ -466,6 +467,7 @@ function ProviderWheel({ options, value, onChange }: ProviderWheelProps) { export function OnboardingPage() { const { t } = useTranslation(['onboarding', 'common']) + const { showToast } = useToast() const { requestOnboardingStep, submitOnboardingStep, @@ -651,6 +653,20 @@ export function OnboardingPage() { const isSubPending = apiKeyProvider ? !!subscriptionPending[apiKeyProvider] : false const subPasteback = apiKeyProvider ? subscriptionPasteback[apiKeyProvider] : undefined + useEffect(() => { + const handleFailure = (data: unknown) => { + const d = data as { provider?: string; success: boolean; message?: string; error?: string } + if (d.provider === apiKeyProvider && !d.success) { + showToast('error', d.message || d.error || t('onboarding:sub.actionFailed')) + } + } + const cleanups = [ + socket.onMessage('model_subscription_connect', handleFailure), + socket.onMessage('model_subscription_disconnect', handleFailure), + ] + return () => cleanups.forEach(cleanup => cleanup()) + }, [apiKeyProvider, socket, showToast, t]) + // Refresh the live subscription status whenever we land on a sub-capable // api_key step, and clear any stale paste-back code entry. useEffect(() => { @@ -668,7 +684,7 @@ export function OnboardingPage() { // OpenAI uses a loopback callback (auto-redirect); xAI/Grok's flow ends on // a "copy this code" page, so it goes through the paste-back flow. Mirrors // the decision in the Settings model panel. - const useLoopback = apiKeyProvider === 'openai' + const useLoopback = apiKeyProvider === 'openai' || apiKeyProvider === 'anthropic' socket.send( useLoopback ? 'model_subscription_connect' : 'model_subscription_prepare', { provider: apiKeyProvider }, @@ -977,6 +993,27 @@ export function OnboardingPage() { )} + {!isSubConnected && subStatus?.configured && ( + <> +

{t('onboarding:sub.recoveryHint')}

+ + + )} + {subStatus?.error &&

{subStatus.error}

} + + {apiKeyProvider === 'anthropic' && ( +

{t('onboarding:sub.claudeProfileNote')}

+ )} + {/* API-key fallback. Collapsed behind a link once connected so the connected card stands alone; always shown otherwise. */} {isSubConnected && !showKeyInput ? ( diff --git a/app/ui_layer/browser/frontend/src/pages/Settings/ModelSettings.tsx b/app/ui_layer/browser/frontend/src/pages/Settings/ModelSettings.tsx index 73c91e71..ccddfb93 100644 --- a/app/ui_layer/browser/frontend/src/pages/Settings/ModelSettings.tsx +++ b/app/ui_layer/browser/frontend/src/pages/Settings/ModelSettings.tsx @@ -265,6 +265,20 @@ export function ModelSettings() { setTestBeforeSave(false) } }), + onMessage('model_subscription_connect', (data: unknown) => { + const d = data as { provider?: string; success: boolean; message?: string; error?: string } + if (d.provider === provider && !d.success) { + showToast('error', d.message || d.error || t('settings:model.subscription.connectFailed')) + } + }), + onMessage('model_subscription_disconnect', (data: unknown) => { + const d = data as { provider?: string; success: boolean; message?: string; error?: string } + if (d.provider !== provider) return + showToast( + d.success ? 'success' : 'error', + d.message || d.error || t('settings:model.subscription.disconnectFailed'), + ) + }), onMessage('ollama_models_get', (data: unknown) => { const d = data as { success: boolean; models: string[] } setOllamaModelsLoading(false) @@ -376,6 +390,9 @@ export function ModelSettings() { }, [provider, isConnected, send, baseUrls]) const currentProvider = providers.find(p => p.id === provider) + const testRequiresKey = !!currentProvider?.requires_api_key && + !apiKeys[provider]?.has_key && !newApiKey.trim() && + !subscriptionOauth[provider]?.connected // Generic /v1/models discovery: fetch whenever the active provider // advertises has_model_discovery (new cloud providers). Ollama keeps its @@ -868,6 +885,9 @@ export function ModelSettings() { const subscriptionBlock = supportsSub && (
+ {provider === 'anthropic' && ( +

{t('settings:model.subscription.claudeProfileNote')}

+ )}
)} + {!isSubConnected && subStatus?.configured && ( + <> +

{t('settings:model.subscription.recoveryHint')}

+ + + )} + {subStatus?.error && ( +

{subStatus.error}

+ )} ) @@ -1148,13 +1187,10 @@ export function ModelSettings() { variant="secondary" onClick={handleTestConnection} disabled={ - isTesting || - (!!currentProvider?.requires_api_key && - !apiKeys[provider]?.has_key) + isTesting || testRequiresKey } title={ - currentProvider?.requires_api_key && - !apiKeys[provider]?.has_key + testRequiresKey ? t('settings:model.actions.testRequiresKey') : '' } diff --git a/app/ui_layer/browser/frontend/src/store/slices/modelSettingsSlice.ts b/app/ui_layer/browser/frontend/src/store/slices/modelSettingsSlice.ts index 2e665430..8edbcb49 100644 --- a/app/ui_layer/browser/frontend/src/store/slices/modelSettingsSlice.ts +++ b/app/ui_layer/browser/frontend/src/store/slices/modelSettingsSlice.ts @@ -20,7 +20,7 @@ export interface ProviderInfo { is_bedrock?: boolean // Subscription OAuth (ChatGPT Plus/Pro, SuperGrok). When true the // settings page shows a "Sign in with " button next to the - // API-key field. Anthropic is intentionally absent. + // API-key field. supports_subscription_oauth?: boolean subscription_label?: string | null subscription_models?: string[] @@ -35,6 +35,8 @@ export interface ProviderInfo { export interface SubscriptionStatus { supported: boolean connected: boolean + configured?: boolean + error?: string email?: string plan?: string expires_at?: number diff --git a/app/ui_layer/browser/frontend/tests/subscription-recovery.html b/app/ui_layer/browser/frontend/tests/subscription-recovery.html new file mode 100644 index 00000000..f6b20434 --- /dev/null +++ b/app/ui_layer/browser/frontend/tests/subscription-recovery.html @@ -0,0 +1 @@ +Subscription recovery fixture
diff --git a/app/ui_layer/browser/frontend/tests/subscription-recovery.test.ts b/app/ui_layer/browser/frontend/tests/subscription-recovery.test.ts new file mode 100644 index 00000000..b004eeb1 --- /dev/null +++ b/app/ui_layer/browser/frontend/tests/subscription-recovery.test.ts @@ -0,0 +1,65 @@ +import { test, expect, type Page } from '@playwright/test' + +async function response(page: Page, type: string, data: Record) { + await page.evaluate(({ type, data }) => { + window.dispatchEvent(new CustomEvent('fixture-response', { detail: { type, data } })) + }, { type, data }) +} + +async function sent(page: Page, type: string) { + return page.evaluate(type => { + const requests = (window as typeof window & { + subscriptionRequests: Array<{ type: string; data: Record }> + }).subscriptionRequests + return requests.filter(request => request.type === type) + }, type) +} + +for (const screen of ['settings', 'onboarding']) { + test(`${screen}: invalid login retains disconnect after failure and clears after verified logout`, async ({ page }) => { + await page.goto(`/tests/subscription-recovery.html?screen=${screen}`) + await expect(page.getByRole('button', { name: 'Sign in with Claude', exact: true })).toBeVisible() + await expect(page.getByRole('alert')).toContainText('Claude login needs recovery.') + const disconnect = page.getByRole('button', { name: 'Disconnect', exact: true }) + await disconnect.click() + expect(await sent(page, 'model_subscription_disconnect')).toEqual([ + { type: 'model_subscription_disconnect', data: { provider: 'anthropic' } }, + ]) + await expect(disconnect).toBeDisabled() + await response(page, 'model_subscription_disconnect', { + success: false, provider: 'anthropic', message: 'Could not verify logout.', + status: { supported: true, configured: true, connected: false, error: 'Could not verify logout.' }, + }) + await expect(disconnect).toBeEnabled() + await expect(page.getByRole('alert')).toContainText('Could not verify logout.') + await disconnect.click() + expect(await sent(page, 'model_subscription_disconnect')).toHaveLength(2) + await response(page, 'model_subscription_disconnect', { + success: true, provider: 'anthropic', + status: { supported: true, connected: false }, + }) + await expect(disconnect).toHaveCount(0) + await expect(page.getByRole('button', { name: 'Sign in with Claude', exact: true })).toBeEnabled() + await expect(page.getByRole('alert')).toHaveCount(0) + if (screen === 'settings') { + await page.getByRole('button', { name: 'Test Connection', exact: true }).click() + expect(await sent(page, 'model_connection_test')).toHaveLength(1) + } + }) + + test(`${screen}: invalid login can sign in again`, async ({ page }) => { + await page.goto(`/tests/subscription-recovery.html?screen=${screen}`) + const signIn = page.getByRole('button', { name: 'Sign in with Claude', exact: true }) + await signIn.click() + expect(await sent(page, 'model_subscription_connect')).toEqual([ + { type: 'model_subscription_connect', data: { provider: 'anthropic' } }, + ]) + await response(page, 'model_subscription_connect', { + success: true, provider: 'anthropic', active_provider: 'anthropic', + status: { supported: true, configured: true, connected: true, email: 'test@example.com' }, + }) + await expect(signIn).toHaveCount(0) + await expect(page.getByRole('button', { name: 'Disconnect', exact: true })).toBeEnabled() + await expect(page.getByRole('alert')).toHaveCount(0) + }) +} diff --git a/app/ui_layer/browser/frontend/tests/subscription-recovery.tsx b/app/ui_layer/browser/frontend/tests/subscription-recovery.tsx new file mode 100644 index 00000000..0543bb4a --- /dev/null +++ b/app/ui_layer/browser/frontend/tests/subscription-recovery.tsx @@ -0,0 +1,56 @@ +// Exercise the real settings/onboarding screens with an isolated saved login. +import React from 'react' +import { createRoot } from 'react-dom/client' +import { Provider } from 'react-redux' +import { MemoryRouter } from 'react-router-dom' +import { getSocketClient } from '../src/store/socket/socketInstance' +import { dispatchInbound } from '../src/store/socket/messageRegistry' +import { setConnected } from '../src/store/slices/connectionSlice' +import { setProviders, setSettings, setSlowModeEnabled, setSubscriptionStatus } from '../src/store/slices/modelSettingsSlice' +import { setStep } from '../src/store/slices/onboardingSlice' +import { ToastProvider } from '../src/contexts/ToastContext' +import { WebSocketProvider } from '../src/contexts/WebSocketContext' +import { ModelSettings } from '../src/pages/Settings/ModelSettings' +import { OnboardingPage } from '../src/pages/Onboarding/OnboardingPage' +import i18n from '../src/i18n/config' +import '../src/styles/global.css' + +const requests: Array<{ type: string; data: Record }> = [] +const client = getSocketClient() +client.connect = () => {} +client.send = (type, data = {}) => { requests.push({ type, data }) } +Object.defineProperty(client, 'isConnected', { get: () => true }) +Object.assign(window, { subscriptionRequests: requests }) +// Bootstrap after substituting the transport so no real backend is contacted. +const { store } = await import('../src/store') +await i18n.changeLanguage('en') +store.dispatch(setConnected(true)) +store.dispatch(setProviders([{ + id: 'anthropic', name: 'Anthropic', requires_api_key: true, + llm_model: 'claude-sonnet-4-6', vlm_model: 'claude-sonnet-4-6', has_vlm: true, + image_gen_model: null, video_gen_model: null, has_image_gen: false, has_video_gen: false, + supports_subscription_oauth: true, subscription_label: 'Sign in with Claude', +}])) +store.dispatch(setSettings({ + provider: 'anthropic', imageGenProvider: 'openai', videoGenProvider: 'gemini', + llmModel: 'claude-sonnet-4-6', vlmModel: 'claude-sonnet-4-6', imageGenModel: '', videoGenModel: '', + apiKeys: { anthropic: { has_key: true, masked_key: 'fake...key' } }, baseUrls: {}, +})) +store.dispatch(setSlowModeEnabled(false)) +store.dispatch(setSubscriptionStatus({ provider: 'anthropic', status: { + supported: true, configured: true, connected: false, error: 'Claude login needs recovery.', +} })) +store.dispatch(setStep({ + name: 'api_key', title: 'Connect Claude', description: 'Sign in or use an API key.', + required: true, index: 2, total: 5, options: [], default: '', provider: 'anthropic', + supports_subscription_oauth: true, subscription_label: 'Sign in with Claude', +})) +window.addEventListener('fixture-response', event => { + dispatchInbound((event as CustomEvent).detail, store.dispatch, store.getState) +}) +const onboarding = new URLSearchParams(location.search).get('screen') === 'onboarding' +createRoot(document.getElementById('root')!).render( + + {onboarding ? : } + , +) diff --git a/app/ui_layer/onboarding/controller.py b/app/ui_layer/onboarding/controller.py index 009a84ee..7e8c3d61 100644 --- a/app/ui_layer/onboarding/controller.py +++ b/app/ui_layer/onboarding/controller.py @@ -323,9 +323,9 @@ def _parse_api_key(raw: Any) -> tuple[str, str, str]: def _subscription_connected(provider: str) -> bool: """True when an OAuth subscription credential is stored for ``provider``.""" try: - from app.ui_layer.settings.provider_settings import get_subscription_status + from craftos_integrations.llm_oauth.tokens import has_credential - return bool(get_subscription_status(provider).get("connected")) + return has_credential(provider) except Exception: return False @@ -361,7 +361,11 @@ def _save_provider( save_settings_to_json("openrouter", api_key) from app.ui_layer.settings.model_settings import update_model_settings - update_model_settings(llm_model=or_model, vlm_model=or_model) + update_model_settings( + llm_model=or_model, + vlm_model=or_model, + include_subscription_status=False, + ) return "openrouter" if provider and api_key: @@ -422,7 +426,9 @@ def _activate_provider(self, provider: str) -> None: if MODEL_REGISTRY.get(provider, {}).get(InterfaceType.IMAGE_GEN): from app.ui_layer.settings.model_settings import update_model_settings - update_model_settings(image_gen_provider=provider) + update_model_settings( + image_gen_provider=provider, include_subscription_status=False + ) if agent: agent.reinitialize_image_gen(provider) logger.info( diff --git a/app/ui_layer/settings/memory_settings.py b/app/ui_layer/settings/memory_settings.py index 19fd1951..5afb1bdf 100644 --- a/app/ui_layer/settings/memory_settings.py +++ b/app/ui_layer/settings/memory_settings.py @@ -10,6 +10,7 @@ from datetime import datetime from typing import Dict, Any, Optional, List +from app.settings_store import settings_transaction, write_settings from app.config import ( AGENT_FILE_SYSTEM_PATH, AGENT_FILE_SYSTEM_TEMPLATE_PATH, @@ -85,6 +86,7 @@ # ───────────────────────────────────────────────────────────────────── +@settings_transaction def _load_settings() -> Dict[str, Any]: """Load settings from settings.json.""" if not SETTINGS_CONFIG_PATH.exists(): @@ -108,9 +110,7 @@ def _load_settings() -> Dict[str, Any]: def _save_settings(settings: Dict[str, Any]) -> bool: """Save settings to settings.json.""" try: - SETTINGS_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) - with open(SETTINGS_CONFIG_PATH, "w", encoding="utf-8") as f: - json.dump(settings, f, indent=2) + write_settings(SETTINGS_CONFIG_PATH, settings) return True except Exception: return False @@ -148,6 +148,7 @@ def get_memory_processing_threshold() -> int: return max(0, min(PROCESSING_THRESHOLD_MAX, raw)) +@settings_transaction def set_memory_processing_threshold(value: int) -> bool: """Persist the threshold-driven processing count (clamped to [0, max]).""" settings = _load_settings() @@ -244,6 +245,7 @@ def get_memory_mode() -> Dict[str, Any]: return {"success": False, "error": f"Failed to get memory mode: {str(e)}"} +@settings_transaction def set_memory_mode(enabled: bool) -> Dict[str, Any]: """Set the memory mode on or off. @@ -652,6 +654,7 @@ def get_memory_indexed_files() -> List[str]: return [str(f) for f in files if isinstance(f, str) and f.strip()] +@settings_transaction def set_memory_indexed_files(paths: List[str]) -> Dict[str, Any]: """Replace the extra indexed-files list. @@ -700,19 +703,20 @@ def set_memory_indexed_files(paths: List[str]) -> Dict[str, Any]: return {"success": False, "error": f"Failed to set indexed files: {str(e)}"} +@settings_transaction def add_memory_indexed_file(path: str) -> Dict[str, Any]: """Add a single file to the extra indexed-files list. Reads the currently persisted list fresh and appends the one path, - reusing set_memory_indexed_files for validation and dedup. Because the - browser adapter processes WebSocket messages serially, concurrent "+" - clicks compose additively instead of clobbering each other: each call - sees the result of the previous one. + reusing set_memory_indexed_files for validation and dedup. The shared + settings transaction keeps concurrent additions from clobbering each + other: each call sees the result of the previous one. """ current = get_memory_indexed_files() return set_memory_indexed_files(current + [path]) +@settings_transaction def remove_memory_indexed_file(path: str) -> Dict[str, Any]: """Remove a single file from the extra indexed-files list. diff --git a/app/ui_layer/settings/model_settings.py b/app/ui_layer/settings/model_settings.py index 6e659de3..f2da5619 100644 --- a/app/ui_layer/settings/model_settings.py +++ b/app/ui_layer/settings/model_settings.py @@ -15,6 +15,7 @@ import httpx from app.config import SETTINGS_CONFIG_PATH +from app.settings_store import settings_transaction, settings_write_lock, write_settings from app.models import ( MODEL_REGISTRY, InterfaceType, @@ -34,6 +35,7 @@ PROVIDER_INFO = _derive_provider_info() +@settings_transaction def _load_settings() -> Dict[str, Any]: """Load settings from settings.json.""" if not SETTINGS_CONFIG_PATH.exists(): @@ -69,9 +71,7 @@ def _load_settings() -> Dict[str, Any]: def _save_settings(settings: Dict[str, Any]) -> bool: """Save settings to settings.json.""" try: - SETTINGS_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) - with open(SETTINGS_CONFIG_PATH, "w", encoding="utf-8") as f: - json.dump(settings, f, indent=2) + write_settings(SETTINGS_CONFIG_PATH, settings) return True except Exception: return False @@ -168,11 +168,14 @@ def get_available_providers() -> Dict[str, Any]: # ───────────────────────────────────────────────────────────────────── -def get_model_settings() -> Dict[str, Any]: +def get_model_settings(*, include_subscription_status: bool = True) -> Dict[str, Any]: """Get current model settings. Returns: Dict with current LLM/VLM provider, models, and API key status + + Live subscription status may run the Claude CLI. Callers on an event + loop must offload this function or omit status when it is unused. """ try: settings = _load_settings() @@ -248,7 +251,9 @@ def get_model_settings() -> Dict[str, Any]: ) for provider_id, info in PROVIDER_INFO.items(): - if not info.get("supports_subscription_oauth"): + if not include_subscription_status or not info.get( + "supports_subscription_oauth" + ): continue subscription_status[provider_id] = _oauth_status(provider_id) except Exception: @@ -331,6 +336,7 @@ def update_model_settings( base_url: Optional[str] = None, provider_for_url: Optional[str] = None, aws_credentials: Optional[Dict[str, str]] = None, + include_subscription_status: bool = True, ) -> Dict[str, Any]: """Update model settings. @@ -345,152 +351,157 @@ def update_model_settings( provider_for_key: Provider to save API key for base_url: Base URL to save (for byteplus/remote) provider_for_url: Provider to save base URL for + include_subscription_status: Include live account checks in the result. + Disable for synchronous onboarding callers that discard the result. Returns: Dict with success status and updated settings """ try: - settings = _load_settings() - if "model" not in settings: - settings["model"] = {} - if "api_keys" not in settings: - settings["api_keys"] = {} - if "endpoints" not in settings: - settings["endpoints"] = {} - if "aws_credentials" not in settings: - settings["aws_credentials"] = {} - - # Update providers - # When provider changes, clear the model override so default model is used - old_llm_provider = settings["model"].get("llm_provider") - old_vlm_provider = settings["model"].get("vlm_provider") - - if llm_provider: - settings["model"]["llm_provider"] = llm_provider - # Clear LLM model if provider changed (unless new model explicitly provided) - if llm_provider != old_llm_provider and llm_model is None: - settings["model"]["llm_model"] = None - - if vlm_provider: - settings["model"]["vlm_provider"] = vlm_provider - # Clear VLM model if provider changed (unless new model explicitly provided) - if vlm_provider != old_vlm_provider and vlm_model is None: - settings["model"]["vlm_model"] = None - elif llm_provider and llm_provider != old_llm_provider: - # If only llm_provider changed and vlm_provider not specified, - # also update vlm_provider to match and clear vlm_model - settings["model"]["vlm_provider"] = llm_provider - if vlm_model is None: - settings["model"]["vlm_model"] = None - - # Update image generation provider (validate before saving) - if image_gen_provider: - supported_img_providers = { - p - for p, caps in MODEL_REGISTRY.items() - if caps.get(InterfaceType.IMAGE_GEN) - } - if image_gen_provider not in supported_img_providers: - return { - "success": False, - "error": ( - f"'{image_gen_provider}' does not support image generation. " - f"Supported providers: {', '.join(sorted(supported_img_providers))}" - ), + with settings_write_lock: + settings = _load_settings() + if "model" not in settings: + settings["model"] = {} + if "api_keys" not in settings: + settings["api_keys"] = {} + if "endpoints" not in settings: + settings["endpoints"] = {} + if "aws_credentials" not in settings: + settings["aws_credentials"] = {} + + # Update providers + # When provider changes, clear the model override so default model is used + old_llm_provider = settings["model"].get("llm_provider") + old_vlm_provider = settings["model"].get("vlm_provider") + + if llm_provider: + settings["model"]["llm_provider"] = llm_provider + # Clear LLM model if provider changed (unless new model explicitly provided) + if llm_provider != old_llm_provider and llm_model is None: + settings["model"]["llm_model"] = None + + if vlm_provider: + settings["model"]["vlm_provider"] = vlm_provider + # Clear VLM model if provider changed (unless new model explicitly provided) + if vlm_provider != old_vlm_provider and vlm_model is None: + settings["model"]["vlm_model"] = None + elif llm_provider and llm_provider != old_llm_provider: + # If only llm_provider changed and vlm_provider not specified, + # also update vlm_provider to match and clear vlm_model + settings["model"]["vlm_provider"] = llm_provider + if vlm_model is None: + settings["model"]["vlm_model"] = None + + # Update image generation provider (validate before saving) + if image_gen_provider: + supported_img_providers = { + p + for p, caps in MODEL_REGISTRY.items() + if caps.get(InterfaceType.IMAGE_GEN) } - old_img_provider = settings["model"].get("image_gen_provider") - settings["model"]["image_gen_provider"] = image_gen_provider - if image_gen_provider != old_img_provider and image_gen_model is None: - settings["model"]["image_gen_model"] = None - - # Update video generation provider (validate before saving) - if video_gen_provider: - supported_vid_providers = { - p - for p, caps in MODEL_REGISTRY.items() - if caps.get(InterfaceType.VIDEO_GEN) - } - if video_gen_provider not in supported_vid_providers: - return { - "success": False, - "error": ( - f"'{video_gen_provider}' does not support video generation. " - f"Supported providers: {', '.join(sorted(supported_vid_providers))}" - ), + if image_gen_provider not in supported_img_providers: + return { + "success": False, + "error": ( + f"'{image_gen_provider}' does not support image generation. " + f"Supported providers: {', '.join(sorted(supported_img_providers))}" + ), + } + old_img_provider = settings["model"].get("image_gen_provider") + settings["model"]["image_gen_provider"] = image_gen_provider + if image_gen_provider != old_img_provider and image_gen_model is None: + settings["model"]["image_gen_model"] = None + + # Update video generation provider (validate before saving) + if video_gen_provider: + supported_vid_providers = { + p + for p, caps in MODEL_REGISTRY.items() + if caps.get(InterfaceType.VIDEO_GEN) } - old_vid_provider = settings["model"].get("video_gen_provider") - settings["model"]["video_gen_provider"] = video_gen_provider - if video_gen_provider != old_vid_provider and video_gen_model is None: - settings["model"]["video_gen_model"] = None - - # Update custom models (explicit values override the auto-clear above) - if llm_model is not None: - settings["model"]["llm_model"] = llm_model if llm_model else None - if vlm_model is not None: - settings["model"]["vlm_model"] = vlm_model if vlm_model else None - if image_gen_model is not None: - settings["model"]["image_gen_model"] = ( - image_gen_model if image_gen_model else None - ) - if video_gen_model is not None: - settings["model"]["video_gen_model"] = ( - video_gen_model if video_gen_model else None - ) - - # Update API key in settings.json - if provider_for_key and api_key is not None: - info = PROVIDER_INFO.get(provider_for_key, {}) - settings_key = info.get("settings_key") - if settings_key: - settings["api_keys"][settings_key] = api_key - - # Update base URL in settings.json. The endpoints key is derived from - # the provider profile so every provider with an endpoint (local - # servers, new cloud providers, custom) persists — not just the - # legacy four. Bedrock's derived slot is aws_region (the "base URL" - # carries the region). - if provider_for_url and base_url is not None: - profile = get_registry().get(provider_for_url) - if profile is None: + if video_gen_provider not in supported_vid_providers: + return { + "success": False, + "error": ( + f"'{video_gen_provider}' does not support video generation. " + f"Supported providers: {', '.join(sorted(supported_vid_providers))}" + ), + } + old_vid_provider = settings["model"].get("video_gen_provider") + settings["model"]["video_gen_provider"] = video_gen_provider + if video_gen_provider != old_vid_provider and video_gen_model is None: + settings["model"]["video_gen_model"] = None + + # Update custom models (explicit values override the auto-clear above) + if llm_model is not None: + settings["model"]["llm_model"] = llm_model if llm_model else None + if vlm_model is not None: + settings["model"]["vlm_model"] = vlm_model if vlm_model else None + if image_gen_model is not None: + settings["model"]["image_gen_model"] = ( + image_gen_model if image_gen_model else None + ) + if video_gen_model is not None: + settings["model"]["video_gen_model"] = ( + video_gen_model if video_gen_model else None + ) + + # Update API key in settings.json + if provider_for_key and api_key is not None: + info = PROVIDER_INFO.get(provider_for_key, {}) + settings_key = info.get("settings_key") + if settings_key: + settings["api_keys"][settings_key] = api_key + + # Update base URL in settings.json. The endpoints key is derived from + # the provider profile so every provider with an endpoint (local + # servers, new cloud providers, custom) persists — not just the + # legacy four. Bedrock's derived slot is aws_region (the "base URL" + # carries the region). + if provider_for_url and base_url is not None: + profile = get_registry().get(provider_for_url) + if profile is None: + return { + "success": False, + "error": f"Unknown provider for base URL: {provider_for_url}", + } + settings["endpoints"][profile.settings_endpoint_key] = base_url + + # Update AWS credentials block (bedrock-only) + if aws_credentials: + for field in ("access_key_id", "secret_access_key", "session_token"): + value = aws_credentials.get(field) + if value is not None: + settings["aws_credentials"][field] = value + region = aws_credentials.get("region") + if region: + settings["endpoints"]["aws_region"] = region + + # Clear remote URL when switching away from remote so stale values don't persist + if ( + llm_provider + and llm_provider != "remote" + and old_llm_provider == "remote" + and not provider_for_url + ): + settings["endpoints"]["remote_model_url"] = "" + + # Save settings.json + if not _save_settings(settings): return { "success": False, - "error": f"Unknown provider for base URL: {provider_for_url}", + "error": "Failed to save settings.json", } - settings["endpoints"][profile.settings_endpoint_key] = base_url - - # Update AWS credentials block (bedrock-only) - if aws_credentials: - for field in ("access_key_id", "secret_access_key", "session_token"): - value = aws_credentials.get(field) - if value is not None: - settings["aws_credentials"][field] = value - region = aws_credentials.get("region") - if region: - settings["endpoints"]["aws_region"] = region - - # Clear remote URL when switching away from remote so stale values don't persist - if ( - llm_provider - and llm_provider != "remote" - and old_llm_provider == "remote" - and not provider_for_url - ): - settings["endpoints"]["remote_model_url"] = "" - - # Save settings.json - if not _save_settings(settings): - return { - "success": False, - "error": "Failed to save settings.json", - } - # Reload settings cache so changes take effect - from app.config import reload_settings + # Reload settings cache so changes take effect + from app.config import reload_settings - reload_settings() + reload_settings() # Return updated settings - return get_model_settings() + return get_model_settings( + include_subscription_status=include_subscription_status + ) except Exception as e: return { @@ -795,6 +806,7 @@ def get_slow_mode_settings() -> Dict[str, Any]: } +@settings_transaction def set_slow_mode(enabled: bool, tpm_limit: Optional[int] = None) -> Dict[str, Any]: """Set slow mode on or off, optionally updating the TPM limit.""" settings = _load_settings() diff --git a/app/ui_layer/settings/proactive_settings.py b/app/ui_layer/settings/proactive_settings.py index 09c15e46..06eb9367 100644 --- a/app/ui_layer/settings/proactive_settings.py +++ b/app/ui_layer/settings/proactive_settings.py @@ -8,6 +8,7 @@ import shutil from typing import Dict, Any, Optional, List +from app.settings_store import settings_transaction, write_settings from app.config import ( AGENT_FILE_SYSTEM_PATH, AGENT_FILE_SYSTEM_TEMPLATE_PATH, @@ -25,6 +26,7 @@ # ───────────────────────────────────────────────────────────────────── +@settings_transaction def _load_settings() -> Dict[str, Any]: """Load settings from settings.json.""" if not SETTINGS_CONFIG_PATH.exists(): @@ -40,9 +42,7 @@ def _load_settings() -> Dict[str, Any]: def _save_settings(settings: Dict[str, Any]) -> bool: """Save settings to settings.json.""" try: - SETTINGS_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) - with open(SETTINGS_CONFIG_PATH, "w", encoding="utf-8") as f: - json.dump(settings, f, indent=2) + write_settings(SETTINGS_CONFIG_PATH, settings) return True except Exception: return False @@ -71,6 +71,7 @@ def get_proactive_mode() -> Dict[str, Any]: return {"success": False, "error": f"Failed to get proactive mode: {str(e)}"} +@settings_transaction def set_proactive_mode(enabled: bool) -> Dict[str, Any]: """Set the proactive mode on or off. diff --git a/app/ui_layer/settings/provider_settings.py b/app/ui_layer/settings/provider_settings.py index 0124231f..a9c2204a 100644 --- a/app/ui_layer/settings/provider_settings.py +++ b/app/ui_layer/settings/provider_settings.py @@ -9,6 +9,7 @@ from app.logger import logger from app.models.provider_config import PROVIDER_CONFIG from app.config import SETTINGS_CONFIG_PATH +from app.settings_store import settings_transaction, write_settings # Provider to settings.json api_keys key mapping — DERIVED from the provider @@ -23,6 +24,7 @@ PROVIDER_TO_SETTINGS_KEY = _derive_settings_keys() +@settings_transaction def _load_settings() -> Dict[str, Any]: """Load settings from settings.json.""" if not SETTINGS_CONFIG_PATH.exists(): @@ -37,15 +39,14 @@ def _load_settings() -> Dict[str, Any]: def _save_settings(settings: Dict[str, Any]) -> bool: """Save settings to settings.json.""" try: - SETTINGS_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) - with open(SETTINGS_CONFIG_PATH, "w", encoding="utf-8") as f: - json.dump(settings, f, indent=2) + write_settings(SETTINGS_CONFIG_PATH, settings) return True except Exception as e: logger.error(f"[SETTINGS] Failed to save settings.json: {e}") return False +@settings_transaction def save_settings_to_json(provider: str, api_key: str) -> bool: """Save provider and API key to settings.json. @@ -103,6 +104,7 @@ def save_settings_to_json(provider: str, api_key: str) -> bool: save_settings_to_env = save_settings_to_json +@settings_transaction def save_remote_endpoint(url: str) -> bool: """Save the Ollama (remote) base URL to settings.json. @@ -139,6 +141,7 @@ def save_remote_endpoint(url: str) -> bool: return False +@settings_transaction def save_custom_provider(name: str, spec: Dict[str, Any]) -> Tuple[bool, str]: """Create or update a user-defined provider (Phase 3, FR-5). @@ -190,6 +193,7 @@ def save_custom_provider(name: str, spec: Dict[str, Any]) -> Tuple[bool, str]: return False, f"Failed to save custom provider: {e}" +@settings_transaction def delete_custom_provider(name: str) -> Tuple[bool, str]: """Remove a custom provider and its stored API key.""" try: @@ -231,13 +235,12 @@ def get_api_key_for_provider(provider: str) -> str: # ───────────────────────────────────────────────────────────────────── -# Subscription OAuth (ChatGPT Plus/Pro/Team, SuperGrok). UI sits in the -# model-settings panel next to the API-key field. Anthropic is intentionally -# excluded — Pro/Max OAuth in third-party tools was forbidden by Anthropic -# in Feb 2026, so we keep that path API-key-only. +# Subscription OAuth. Claude subscriptions use the official Claude Code CLI +# for both login and inference; CraftBot stores only a local connection flag. # ───────────────────────────────────────────────────────────────────── +@settings_transaction def _persist_auth_mode(provider: str, mode: str) -> None: """Write the UI-hint ``auth_mode`` for ``provider`` to settings.json. @@ -257,7 +260,7 @@ def _persist_auth_mode(provider: str, mode: str) -> None: async def connect_subscription_async(provider: str) -> Tuple[bool, str]: - """Launch the subscription OAuth flow for ``provider`` (openai / grok). + """Launch the subscription OAuth flow (or Claude Code's own login). Opens the browser, waits for the loopback callback, persists the credential under ``.credentials/_oauth.json``. Async because @@ -288,14 +291,16 @@ async def connect_subscription_async(provider: str) -> Tuple[bool, str]: def disconnect_subscription(provider: str) -> Tuple[bool, str]: """Remove the subscription credential and flip auth_mode back to api_key. - Synchronous — disconnect is just a file delete, no OAuth dance required. + Claude Code also signs out its CraftBot-specific CLI profile. Async + callers should offload this function because the CLI may take time. """ try: from craftos_integrations.llm_oauth import tokens as _oauth_tokens except Exception as e: return False, f"Subscription OAuth backend unavailable: {e}" success, message = _oauth_tokens.disconnect(provider) - _persist_auth_mode(provider, "api_key") + if success: + _persist_auth_mode(provider, "api_key") return success, message diff --git a/craftos_integrations/llm_oauth/README.md b/craftos_integrations/llm_oauth/README.md index 85689e39..b935cb93 100644 --- a/craftos_integrations/llm_oauth/README.md +++ b/craftos_integrations/llm_oauth/README.md @@ -1,17 +1,16 @@ # LLM subscription OAuth -Connect a consumer ChatGPT Plus/Pro/Team or SuperGrok subscription and have +Connect a ChatGPT, SuperGrok, or Claude subscription and have CraftBot consume that quota instead of a paid API key. ## What this module is This is not a normal integration. There is no `BasePlatformClient`, no listener machinery, and nothing shows up in the integrations grid. It's an -auth-only backend that the LLM model factory consults before constructing -an OpenAI client. If a subscription is connected for a given provider, the -factory builds the client in subscription mode (different base URL, bearer -token sourced from OAuth, extra headers); otherwise it falls back to the -stored API key. +authentication backend that the LLM model factory consults before constructing +a client. Connected OpenAI-compatible subscriptions use an OAuth bearer, +provider headers and a subscription endpoint. Connected Claude subscriptions +use a Claude Code CLI client. Otherwise the factory uses the stored API key. ``` agent_core/core/models/factory.py @@ -22,19 +21,38 @@ craftos_integrations/llm_oauth/tokens.py │ │ routes to provider backend ▼ -chatgpt.py / grok.py +chatgpt.py / grok.py / claude_code.py │ ├── OAuthFlow (PKCE, loopback browser callback) └── credentials_store (.credentials/_oauth.json) ``` +Claude Code owns its tokens. `claude_code.py` stores only CraftBot's opt-in +and the factory constructs a CLI client rather than requesting a bearer. + ## Supported providers | Provider | Status | Notes | |---|---|---| | **ChatGPT** Plus/Pro/Team | Works end-to-end | Chat Completions calls are translated to Codex Responses API via [`ChatGPTSubscriptionClient`](../../../../agent_core/core/models/chatgpt_subscription_client.py). Multi-turn history accumulation on this path is handled in [`interface.py`](../../../../agent_core/core/impl/llm/interface.py) so `store=false` doesn't break sub-agent continuity or prefix caching. | | **Grok** SuperGrok / X Premium+ | Works end-to-end | Subscription tokens hit the same `api.x.ai/v1` host as API-key mode, so no call-shape change is needed. | -| **Anthropic** Pro/Max | **Intentionally not implemented** | Anthropic explicitly forbade third-party OAuth subscription use in Feb 2026 (ToS update + server-side block). Adding it would break within weeks and violate ToS. Anthropic stays API-key-only. | +| **Claude** subscription via Claude Code | Implemented; live inference depends on the CLI account's access | Uses the official, unmodified Claude Code CLI for login and inference. CraftBot never reads or stores Claude OAuth tokens. API-key mode remains available. | + +### Claude subscription setup + +1. Install the official [Claude Code CLI](https://code.claude.com/docs/en/setup) on the machine running CraftBot. CraftBot finds `claude` on its PATH, or in the native installer's `~/.local/bin` when CraftBot was started before the install. Windows npm installations also need `node` on PATH. +2. In Settings → Model, select **Anthropic** and click **Sign in with Claude**. The same option is available during onboarding. It works like ChatGPT's sign-in: the button shows a spinner while CraftBot runs `claude auth login` for a **separate CraftBot login profile**, the CLI opens one sign-in tab, and approving there redirects to the CLI's local callback. The CLI exchanges the code with its own PKCE verifier and stores the tokens; CraftBot connects as soon as the CLI reports success. If the profile is already signed in, Connect succeeds without a browser. An unapproved sign-in is stopped after 5 minutes, and clicking Connect again replaces it. This needs a browser on the machine running CraftBot. On a remote server, Claude's page shows a code instead, which CraftBot doesn't accept; use an API key there. +3. Use **Test connection** to verify the selected model. +4. **Disconnect signs out** with `claude auth logout` in CraftBot's private profile, verifies that it is logged out, and then removes the connection flag. Your standalone Claude Code login is untouched. Reconnecting starts a new browser sign-in. A logout/verification failure retains the connection flag and reports an error. + +Claude Code owns credentials and refresh inside `/.credentials/claude_code/`. Every login, status, logout and inference subprocess receives this absolute path as `CLAUDE_CONFIG_DIR`, overriding inherited profile settings without changing the parent environment. CraftBot stores only `{"enabled": true, "profile_version": 1}` in `.credentials/anthropic_claude_code.json`; `tokens.get_bearer("anthropic")` never exports a token. Tokens are written and read by the official CLI, never copied from the standalone login or sent to the Anthropic SDK. Old shared-login flags are ignored until the user signs in to the separate profile. + +Inference uses documented CLI print mode, with built-in tools, MCP configuration, hooks and session persistence disabled. CraftBot retains its own agent loop. Text and images are supported; multi-turn history is sent as a labelled transcript in a single user message. CLI startup adds latency to each request. API-specific cache markers and temperature are not forwarded; usage and cache counts come from the CLI result. CLI model availability and subscription limits apply, and inference errors never silently fall back to a paid API key. + +See the [CLI reference](https://code.claude.com/docs/en/cli-reference) and [Anthropic's authentication guidance](https://code.claude.com/docs/en/legal-and-compliance) for the supported Claude Code route. + +Browser test results, screenshots and remaining acceptance steps are in the +[Claude subscription validation report](../../docs/CLAUDE_CODE_VALIDATION.md). ## Settings UI surface diff --git a/craftos_integrations/llm_oauth/__init__.py b/craftos_integrations/llm_oauth/__init__.py index d7d55556..d52dfb7e 100644 --- a/craftos_integrations/llm_oauth/__init__.py +++ b/craftos_integrations/llm_oauth/__init__.py @@ -15,9 +15,8 @@ calls it before constructing an LLM client; if it returns a token + headers, the client is built in subscription mode and bypasses the stored API key. -WHAT IS DELIBERATELY NOT HERE: Anthropic Claude Max/Pro OAuth. Anthropic -explicitly forbade third-party tools from using Pro/Max OAuth tokens in -Feb 2026. We do not implement it. Anthropic stays API-key-only. +Claude subscription access delegates login and inference to the official, +unmodified Claude Code CLI. CraftBot never reads or stores its OAuth tokens. """ from __future__ import annotations diff --git a/craftos_integrations/llm_oauth/claude_code.py b/craftos_integrations/llm_oauth/claude_code.py new file mode 100644 index 00000000..9e777a89 --- /dev/null +++ b/craftos_integrations/llm_oauth/claude_code.py @@ -0,0 +1,345 @@ +"""Claude subscription access through the unmodified Claude Code CLI. + +CraftBot stores a versioned opt-in flag. Claude Code owns login, tokens and +refresh inside CraftBot's private CLI config directory. The standalone CLI +login is never read, copied or signed out. + +Sign-in works like ChatGPT's: ``claude auth login`` opens one browser tab, +approving there redirects to the CLI's local callback, and the CLI exchanges +the code with its own PKCE verifier and stores the tokens. CraftBot only +waits for the CLI to finish, so it never holds anything it could use to +authenticate. +""" + +from __future__ import annotations + +import asyncio +import json +import os +import re +import shutil +import subprocess +import threading +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +from ..config import ConfigStore +from ..credentials_store import load_credential, remove_credential, save_credential + +CRED_FILE = "anthropic_claude_code.json" +PROFILE_VERSION = 1 +INSTALL_MESSAGE = ( + "Claude Code CLI is required. Install it from " + "https://code.claude.com/docs/en/setup, then connect again." +) +# How long Connect waits for the user to approve in the browser. +LOGIN_TIMEOUT_SECONDS = 5 * 60 +_PASTE_PROMPT = re.compile(r"^.*Paste code here if prompted\s*>\s*") + + +@dataclass +class ClaudeCodeConnection: + enabled: bool = True + # Old markers borrowed the standalone CLI login. Never adopt them into + # the new profile without a separate login through CraftBot. + profile_version: int = 0 + + +def profile_directory() -> Path: + """Private, stable auth directory for this CraftBot installation.""" + path = (ConfigStore.project_root / ".credentials" / "claude_code").resolve() + path.mkdir(parents=True, exist_ok=True, mode=0o700) + return path + + +def _native_install() -> Path: + """Where the native installer puts ``claude``. An app started before the + install still has the old PATH, so this location is checked as well.""" + return ( + Path.home() / ".local" / "bin" / ("claude.exe" if os.name == "nt" else "claude") + ) + + +def cli_command() -> list[str]: + """Resolve a native CLI or npm entrypoint without passing through a shell.""" + command = shutil.which("claude") + if not command and _native_install().is_file(): + command = str(_native_install()) + if not command: + raise RuntimeError(INSTALL_MESSAGE) + path = Path(command) + if path.suffix.lower() in (".cmd", ".bat", ".ps1"): + # Windows npm shims invoke a shell, which can reinterpret arguments. + # Execute the same published JS entrypoint directly with Node instead. + entrypoint = path.parent / "node_modules/@anthropic-ai/claude-code/cli.js" + node = shutil.which("node") + if node and entrypoint.is_file(): + return [node, str(entrypoint)] + raise RuntimeError(INSTALL_MESSAGE) + return [command] + + +def cli_environment() -> Dict[str, str]: + """Always use CraftBot's CLI profile, never the standalone CLI account.""" + env = dict(os.environ) + for name in ( + "ANTHROPIC_API_KEY", + "ANTHROPIC_AUTH_TOKEN", + "ANTHROPIC_BASE_URL", + "CLAUDE_CODE_OAUTH_TOKEN", + "CLAUDE_CODE_USE_BEDROCK", + "CLAUDE_CODE_USE_VERTEX", + "CLAUDE_CODE_USE_FOUNDRY", + "CLAUDECODE", + "CLAUDE_CODE_ENTRYPOINT", + # CraftBot's per-request reasoning choice owns these settings. + "MAX_THINKING_TOKENS", + "CLAUDE_CODE_EFFORT_LEVEL", + "CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING", + ): + env.pop(name, None) + env["CLAUDE_CONFIG_DIR"] = str(profile_directory()) + return env + + +def run_cli(args: list[str], *, timeout: float, env_overrides=None, **kwargs): + env = cli_environment() + env.update(env_overrides or {}) + # Request-specific generation settings must not redirect authentication. + env["CLAUDE_CONFIG_DIR"] = str(profile_directory()) + return subprocess.run( + [*cli_command(), *args], + env=env, + capture_output=True, + text=True, + encoding="utf-8", + timeout=timeout, + creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0, + **kwargs, + ) + + +def _read_auth_status() -> Dict[str, Any]: + result = run_cli(["auth", "status"], timeout=10) + data = json.loads(result.stdout) + if not isinstance(data, dict) or not isinstance(data.get("loggedIn"), bool): + raise ValueError("Invalid authentication status") + if result.returncode not in (0, 1) or (result.returncode and data["loggedIn"]): + raise RuntimeError("Claude Code authentication check failed") + return data + + +def auth_status() -> Dict[str, Any]: + try: + data = _read_auth_status() + if not data["loggedIn"]: + return { + "connected": False, + "error": "Use Connect to sign in to CraftBot's separate Claude profile.", + } + if data.get("authMethod") != "claude.ai": + return { + "connected": False, + "error": "A Claude subscription login is required. Use Connect in CraftBot.", + } + return { + "connected": True, + "email": data.get("email") or "", + "plan": data.get("subscriptionType") or "Claude Code", + } + except subprocess.TimeoutExpired: + return { + "connected": False, + "error": "Claude Code authentication check timed out.", + } + except (OSError, RuntimeError, ValueError): + return { + "connected": False, + "error": "Could not check Claude Code login. " + INSTALL_MESSAGE, + } + + +def has_credential() -> bool: + connection = load_credential(CRED_FILE, ClaudeCodeConnection) + return ( + connection is not None + and connection.enabled + and connection.profile_version == PROFILE_VERSION + ) + + +def status() -> Dict[str, Any]: + if not has_credential(): + return {"supported": True, "connected": False} + # Authentication can fail while the explicit opt-in still owns routing. + # Keep Disconnect available until logout is verified and the flag is removed. + return {"supported": True, "configured": True, **auth_status()} + + +def _save_connection(current: Dict[str, Any]) -> Tuple[bool, str]: + """Record the opt-in once the private profile is signed in to claude.ai.""" + if not current["connected"]: + return False, str(current.get("error", "Claude Code sign-in failed.")) + save_credential(CRED_FILE, ClaudeCodeConnection(profile_version=PROFILE_VERSION)) + if not has_credential(): + return False, "Could not save the Claude Code connection." + who = f" as {current['email']}" if current.get("email") else "" + return True, f"Claude subscription connected{who}." + + +_login_lock = threading.Lock() +_login_process: Optional[subprocess.Popen] = None +_login_generation = 0 + + +def _cancel_login() -> None: + """Invalidate every older attempt and reap its CLI before changing auth. + + Caller holds _login_lock. Never wait for browser approval under this lock. + """ + global _login_generation, _login_process + _login_generation += 1 + process = _login_process + if process is not None: + if process.poll() is None: + process.kill() + process.wait(timeout=5) + _login_process = None + + +def _finish_login(attempt: int, current: Dict[str, Any]) -> Tuple[bool, str]: + with _login_lock: + if attempt != _login_generation: + return False, "Claude sign-in was cancelled or replaced by a newer request." + return _save_connection(current) + + +def _last_message(output: List[str]) -> str: + for line in reversed(output): + line = _PASTE_PROMPT.sub("", line).strip() + if line: + return line + return "" + + +def _browser_login(attempt: int) -> Tuple[bool, str]: + """Run ``claude auth login`` until the user approves in its browser tab.""" + global _login_process + try: + with _login_lock: + if attempt != _login_generation: + return ( + False, + "Claude sign-in was cancelled or replaced by a newer request.", + ) + process = subprocess.Popen( + # Subscription OAuth is the CLI default. Avoid undocumented + # flags that older supported CLIs reject before opening a tab. + [*cli_command(), "auth", "login"], + env=cli_environment(), + # Never written, but kept open: at end of input the CLI would + # stop waiting for the browser. + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0, + ) + _login_process = process + except RuntimeError as e: + return False, str(e) + except OSError as e: + return False, f"Could not start Claude Code: {e}" + output: List[str] = [] + + def read_output() -> None: + for raw in iter(process.stdout.readline, b""): + output.append(raw.decode("utf-8", "replace").strip()) + + reader = threading.Thread(target=read_output, daemon=True) + reader.start() + try: + process.wait(timeout=LOGIN_TIMEOUT_SECONDS) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + return False, "Claude sign-in timed out. Click Connect to try again." + finally: + with _login_lock: + replaced = attempt != _login_generation + if not replaced and process.poll() is not None: + _login_process = None + reader.join(timeout=5) + if replaced: + return False, "A newer Claude sign-in replaced this one." + if process.returncode: + detail = _last_message(output) or "Claude Code could not sign in" + return False, f"Claude sign-in failed: {detail}" + return _finish_login(attempt, auth_status()) + + +def _login() -> Tuple[bool, str]: + # Reserve an identity before even checking an existing private sign-in: + # Disconnect must also invalidate that fast path and post-approval checks. + with _login_lock: + try: + _cancel_login() + except (OSError, subprocess.TimeoutExpired): + return False, "Could not stop the previous Claude sign-in. Retry Connect." + attempt = _login_generation + # A sign-in the private profile already has needs no browser. + current = auth_status() + if current["connected"]: + return _finish_login(attempt, current) + return _browser_login(attempt) + + +async def run_login() -> Tuple[bool, str]: + """Sign in like ChatGPT's loopback flow: Claude Code opens one browser + tab, and this returns once the user approves there or the wait times out.""" + return await asyncio.to_thread(_login) + + +def remove() -> Tuple[bool, str]: + """Sign out only CraftBot's official CLI profile, then clear its marker.""" + # Serialize logout with starting a CLI and committing a connection flag. + # Killing and reaping first prevents a pending CLI from writing auth later. + with _login_lock: + try: + _cancel_login() + except (OSError, subprocess.TimeoutExpired): + return False, "Could not stop the pending Claude sign-in. Retry Disconnect." + return _remove_connection() + + +def _remove_connection() -> Tuple[bool, str]: + try: + result = run_cli(["auth", "logout"], timeout=30) + if result.returncode: + return ( + False, + "Claude sign-out failed. Retry Disconnect; the connection was retained.", + ) + if _read_auth_status()["loggedIn"]: + return ( + False, + "Claude Code is still signed in to CraftBot's profile. Retry Disconnect.", + ) + except subprocess.TimeoutExpired: + return False, "Claude sign-out or verification timed out. Retry Disconnect." + except (OSError, RuntimeError, ValueError): + return ( + False, + "Could not verify Claude sign-out. Check the CLI installation and retry Disconnect.", + ) + try: + remove_credential(CRED_FILE) + except OSError: + return ( + False, + "Claude signed out, but CraftBot could not clear the connection. Retry Disconnect.", + ) + return ( + True, + "Signed out of CraftBot's Claude profile. Your standalone Claude Code login is unchanged.", + ) diff --git a/craftos_integrations/llm_oauth/tokens.py b/craftos_integrations/llm_oauth/tokens.py index f478b3b3..5883fd61 100644 --- a/craftos_integrations/llm_oauth/tokens.py +++ b/craftos_integrations/llm_oauth/tokens.py @@ -10,12 +10,16 @@ else: # fall back to stored API key -The provider arg is the LLM-factory provider name (``openai``, ``grok``), +The provider arg is the LLM-factory provider name (``openai``, ``grok``, ``anthropic``), NOT the OAuth credential slug — the mapping lives here. Returning ``None`` means "no subscription connected; caller should fall back". A raised ``RuntimeError`` means "connected but the refresh blew up" — caller should surface the message so the user can reconnect. +Claude subscriptions use the official Claude Code CLI instead of exporting a +bearer. Their connect/status/disconnect operations share this facade, while +the model factory constructs a CLI client from their local connection flag. + Refresh contract: every call checks the on-disk credential, refreshes if it expires in <5 min, persists the new tokens, returns a still-fresh access token. We do NOT cache in memory — settings.json + .credentials/ remain the @@ -41,9 +45,12 @@ def _lock_for(provider: str) -> threading.Lock: # The factory's provider name → the OAuth backend module that handles it. -# Anthropic is intentionally absent: Pro/Max OAuth is forbidden by ToS -# since Feb 2026. Adding it here would silently re-enable a banned path. +# Anthropic delegates sign-in and inference to the official Claude Code CLI. def _backend_for(provider: str): + if provider == "anthropic": + from . import claude_code + + return claude_code if provider == "openai": from . import chatgpt @@ -77,6 +84,9 @@ def get_bearer(provider: str) -> Optional[Tuple[str, Optional[str], Dict[str, st backend = _backend_for(provider) if backend is None: return None + # Claude Code owns its OAuth credentials; there is no bearer to export. + if not hasattr(backend, "load_and_refresh"): + return None if not backend.has_credential(): return None with _lock_for(provider): @@ -94,7 +104,7 @@ def get_bearer(provider: str) -> Optional[Tuple[str, Optional[str], Dict[str, st def has_credential(provider: str) -> bool: - """True if there's an OAuth credential on disk for this provider.""" + """True if there's an OAuth credential or CLI opt-in for this provider.""" backend = _backend_for(provider) return backend is not None and backend.has_credential() @@ -104,6 +114,8 @@ def status(provider: str) -> Dict[str, object]: backend = _backend_for(provider) if backend is None: return {"supported": False, "connected": False} + if hasattr(backend, "status"): + return backend.status() if not backend.has_credential(): return {"supported": True, "connected": False} cred = backend.load() @@ -128,8 +140,8 @@ async def connect(provider: str) -> Tuple[bool, str]: def disconnect(provider: str) -> Tuple[bool, str]: - """Remove stored OAuth credentials. No server-side revocation — - refresh tokens expire on their own.""" + """Disconnect a subscription. Claude Code logs out its dedicated profile; + other backends remove their stored credential without remote revocation.""" backend = _backend_for(provider) if backend is None: return False, f"Subscription auth not supported for '{provider}'" diff --git a/craftos_integrations/providers/supabase/client.py b/craftos_integrations/providers/supabase/client.py index 521ea6a6..338f94c3 100644 --- a/craftos_integrations/providers/supabase/client.py +++ b/craftos_integrations/providers/supabase/client.py @@ -206,7 +206,8 @@ def _sql_statements(query: str) -> List[str]: in_dollar = None if in_dollar == token else (in_dollar or token) buf.append(token) elif token == ";" and not in_dollar: - parts.append("".join(buf)); buf = [] + parts.append("".join(buf)) + buf = [] else: buf.append(token) parts.append("".join(buf)) diff --git a/docs/CLAUDE_CODE_VALIDATION.md b/docs/CLAUDE_CODE_VALIDATION.md new file mode 100644 index 00000000..c3851ed3 --- /dev/null +++ b/docs/CLAUDE_CODE_VALIDATION.md @@ -0,0 +1,221 @@ +# Claude subscription validation report + +## Final closure pass: 21 October 2026 + +- Model Save, subscription activation and Disconnect share one browser-adapter + lock across persistence, live reinitialization and media rollback. CLI status + runs afterward, outside that lock. Delayed Save responses refresh persisted + values before broadcasting, so they cannot restore an older provider selector. +- Claude sign-in attempts have generation identities. Disconnect invalidates + existing-account checks, pending browser sign-in and post-approval status + checks. It kills and reaps the pending CLI before logout, and connection flags + are committed only while the attempt is still current. A failed process stop + retains the connection and offers a retry. A newer Connect replaces an older + attempt without waiting for browser approval. +- Subscription handlers also discard superseded activation requests, covering + the gap between credential completion and acquiring the model-change lock. +- The installed official CLI 2.1.50 rejected the old `--claudeai` login flag. + Login now uses the documented default `claude auth login`, with the existing + `authMethod == "claude.ai"` verification before saving an opt-in. + See the [official CLI reference](https://code.claude.com/docs/en/cli-reference). + The real CLI now starts browser authorization in the isolated private profile. +- **13 new concurrency regression cases** cover every login phase, process-stop + failure, save/activation ordering across Save, Connect, Complete and Disconnect, + media rollback ordering, and a full handler/auth/settings/factory workflow + through cancellation, fresh reconnect and verified logout. +- **1,104 Python tests passed** in the combined subscription, transactions, + reinitialization, factory, LLM, context-budget, Supabase and WebSocket suites. + **65 additional Mini Browser settings tests passed**: **1,169 total**. +- **4 browser recovery tests passed**. TypeScript, the production build, + repository-wide Ruff lint, changed-file formatting, compilation and whitespace + checks passed. The production build retains its existing bundle-size warning. +- Bounded code review: both reported races are closed; no further code blockers + identified. GitHub reports the PR mergeable against `V1.4.4`; no CI checks + are configured/reported for this head, so the test evidence above is local. +- Real-account acceptance was attempted, but the user could not sign in during + this pass. The pending validation CLI was stopped, the isolated private profile + was logged out and left without a connection flag, and standalone CLI login + remained connected. Authenticated login, live text/image inference and + authenticated logout/reconnect are **unverified**, not claimed as passing. + This is the only remaining acceptance item before a fully validated merge. + +## Earlier review fixes: 21 October 2026 + +- Claude Code now receives an explicit thinking disable override when the + Messages transport omits thinking for an Off choice. The model reasoning + registry determines whether omission means Off, preserving provider defaults + on models that think by default. Inherited CLI reasoning preferences are + removed before applying the request's choice. +- Browser settings reads, saves, rollbacks and subscription activation offload + live subscription checks. Live interface reinitialization stays on the event + loop. Synchronous onboarding validates the saved connection flag and skips + unused live status in settings-update results. +- Invalid Claude authentication now reports the saved connection separately + from live login status. Onboarding and Model settings keep Disconnect + available, explain how to switch to an API key, and display the CLI error. + Failed logout verification retains recovery controls; verified logout clears + the connection and permits explicit API-key use without silent fallback. +- Settings mutations share a reentrant lock across model, provider/auth-mode, + language, memory, proactive and Mini Browser settings. Reads and atomic file + replacement use the same lock; the complete load/change/save transaction is + serialized, while live CLI status checks stay outside it. Failed replacement + leaves the previous file intact. +- The shared subscription button label is **Sign in with Claude** in both + onboarding and Model settings. +- Removed the stale OmniRoute test case while retaining the request-shaping + checks on LM Studio. This exposed a context-budget bug: Chat Completions + reserved the uncapped output limit even when the request used a lower + provider ceiling. The context check now reserves the value actually sent, + with boundary regressions for Qwen, Groq, NVIDIA and Cerebras. +- Focused subscription/reinitialization/settings-transaction tests: **67 passed**, + including 30 new regression cases for reasoning, event-loop isolation, + authentication recovery and concurrent settings mutations. +- Combined subscription, reinitialization, factory, reasoning, golden-payload, + reliability, session-resume, context-readout, context-budget, settings-transaction + and Supabase conformance tests: **1047 passed**. + `test_provider_request_quirks` now passes. +- Additional Mini Browser settings regressions: **65 passed** + (**1112 Python tests passed** across the validation runs). +- Browser recovery regressions: **4 passed**, exercising the real onboarding + and Model settings components with an isolated transport. Both screens can + reconnect, retry failed logout and remove recovery controls after verified + logout. Frontend production build and TypeScript checks pass. +- Real installed Claude Code 2.1.50 against a local stub server: Off omits + thinking from the Messages request; High sends adaptive thinking with effort + high. Both return the stub response through `ClaudeCodeClient`. No real + account credentials or paid model requests were used for this check. +- Repository-wide lint passes after removing the redundant late SQLite import + and splitting the Supabase SQL parser's statements onto separate lines. + Changed Python code passes formatting, compilation and whitespace checks. + +Authenticated private-profile login/logout and live inference acceptance remain +pending as described below. + +## Current implementation: separate Claude login profile + +Updated on 20 October 2026 to implement option 3. CraftBot now uses its own Claude Code profile at `/.credentials/claude_code/`. Login, authentication checks, logout and inference all use that profile. The standalone CLI's account and inherited `CLAUDE_CONFIG_DIR` are not adopted. + +**Disconnect now signs out the private profile**, verifies it is logged out, then removes CraftBot's connection flag. Failure or timeout keeps the flag and reports an error. Disconnect runs off the UI event loop. Reconnect starts a fresh browser login; old shared-login markers require a new sign-in and never migrate tokens. + +- Focused subscription/model factory tests: **32 passed**. Coverage includes profile isolation for every CLI command, legacy-marker migration, failed/logout timeout handling, auth-mode preservation, and a new login after logout. +- Frontend build and TypeScript checks: passed after the profile change. Python lint and formatting checks passed. +- Real CLI isolation smoke test: standalone login was connected before and after a logout of CraftBot's logged-out private profile. CraftBot's private profile correctly reported logged out while standalone Claude Code reported logged in. No standalone credentials were copied or changed. +- The validation app has been restarted with the new backend. **A first login to the private profile and a successful model response still require user validation.** The empty-profile logout smoke test does not establish authenticated OAuth logout against a real account. + +The settings and onboarding screens explain the separate login and scoped disconnect. For manual login recovery, use the command supplied by CraftBot, which sets `CLAUDE_CONFIG_DIR` to the private profile; bare `claude auth login` targets the standalone CLI instead. + +Browser verification after restart confirmed that the old shared email is no longer shown, Connect is available, the separate-profile explanation is visible, and Test Connection stays disabled until the new profile is authenticated. + +![Separate Claude profile awaiting its own sign-in](validation/claude-code/08-independent-profile.jpg) + +### Browser retest: 20 October 2026 + +Retested the current implementation at [Settings → Model](http://localhost:27955/settings), using the real frontend and backend. The focused subscription/model-factory suite was rerun during this session: **32 passed in 14.93 seconds**. + +| Check | Result | Evidence | +| --- | --- | --- | +| Start disconnected without adopting the standalone account | Pass | Connect is available, the shared email is absent, and Test Connection is disabled. Screenshot 9. | +| Explain the private profile and scoped logout | Pass | Settings says sign-in is separate and Disconnect does not affect standalone Claude Code. Screenshot 9. | +| Click Connect | Pass: login initiated | The button changes to disabled “Opening browser…”. A real official CLI `auth login` process starts under the validation backend. Screenshot 10. | +| Establish an authenticated private profile | Awaiting user sign-in | At the checkpoint after clicking Connect, the private CLI status is logged out and CraftBot has no connection marker. The pending UI is not proof of successful browser authorization. | +| Disconnect an authenticated profile, then reconnect | Pending | Requires completion of the first private-profile sign-in. Mocked tests cover logout verification and a new login on reconnect, but are not a real-account browser test. | +| Preserve standalone CLI authentication | Partial | The earlier empty-profile logout smoke test preserved the standalone login. Preservation during an authenticated private-profile logout still needs verification. | + +#### 9. Before Connect: separate profile is disconnected + +![Settings before connecting the private Claude profile](validation/claude-code/09-private-profile-before-connect.jpg) + +#### 10. After Connect: real login is pending + +![Settings waiting for the official Claude Code browser sign-in](validation/claude-code/10-private-profile-login-pending.jpg) + +The user was asked to complete Anthropic's sign-in in the browser opened by Claude Code. No credentials were copied from the standalone profile, and no successful login, authenticated logout, or inference is claimed from this pending state. + +### Current manual acceptance + +1. Open [CraftBot](http://localhost:27955/settings) and select Model. The previous shared account must no longer appear connected. +2. Click **Sign in with Claude** and complete Anthropic's own browser sign-in for the CraftBot profile. +3. Run Test Connection. Account entitlement and model access still apply. +4. Disconnect, confirm the private profile is logged out, then reconnect and confirm a browser sign-in is required again. +5. Confirm the standalone Claude Code CLI remains signed in throughout. + +## Earlier shared-login validation (superseded) + +The results and six screenshots below document the earlier implementation. They do **not** establish login/logout behavior for the new private profile. In particular, the previous opt-in-only disconnect and automatic adoption of the standalone CLI login have been replaced. + +Tested on 20 October 2026 using the running CraftBot application and its real browser UI. Subscription connection, configuration persistence, disconnect and reconnect passed. Successful model inference was blocked by that Claude account's organization access; the application displayed that failure correctly. + +## Open the validation instance + +In the earlier run, Anthropic was connected, with the LLM set to `claude-haiku-4-5-20251001` and VLM set to `claude-sonnet-4-6`. The new profile starts disconnected and requires its own login. + +This run uses the current worktree's code, frontend port **27955**, backend port **27956**, and a separate `CRAFTBOT_HOME` under this chat's `craftbot-validation/state` output directory. Normal CraftBot settings and credentials were not edited. Scheduled work, proactive work and memory processing are disabled in the validation settings. The standalone Claude Code login is reused. + +## Browser checks + +| Check | Result | Evidence | +| --- | --- | --- | +| Start the real frontend and agent backend | Pass | Both ports are listening; the application completed startup. | +| Select Anthropic during fresh onboarding | Pass | Claude subscription button and API-key alternative are visible. Screenshot 1. | +| Connect without an API key | Pass | Existing CLI login is reused; Connected state appears and Next becomes available. Screenshot 2. | +| Finish onboarding without an API key | Pass | Optional personal details were skipped; the main application opens. | +| Test a connected subscription from Model settings | Pass after fix | Test Connection is enabled without an API key. Screenshot 3. | +| Perform a real model request | Blocked by account | Claude returns the organization-access error shown below. Screenshot 4. | +| Save a model change without an API key | Pass | Saved Haiku as the LLM; the selected model and subscription remain after browser reload. Screenshot 5. | +| Disconnect | Pass | Subscription flag is removed, API-key input returns, and Test Connection becomes disabled while no credential is supplied. Screenshot 6. | +| Preserve the standalone CLI login | Pass | CLI authentication status still reports connected after CraftBot disconnects. | +| Reconnect | Pass | Existing CLI login is reused again and Test Connection is enabled. | +| Keep OAuth tokens out of CraftBot | Pass | The only stored Claude connection data is `{"enabled": true}`. | + +The real request returned: + +> Claude Code inference failed: Your organization does not have access to Claude. Please login again or contact your administrator. + +CraftBot's Connected badge confirms that a CLI login is available; it does not establish that the account can run the selected model. A successful inference response, image interpretation, and a fresh browser OAuth authorization remain unverified. No new OAuth authorization was necessary because Claude Code was already signed in. Paid API-key inference was not tested because no Anthropic API key was supplied. + +## Fix found during browser testing + +The Model settings **Test Connection** button previously required a stored API key even when subscription authentication was connected. Its disabled state and tooltip now recognize a connected subscription or a newly entered API key. The frontend was rebuilt, reloaded in the browser, and the real subscription test was run using the corrected button. + +## Automated checks + +- Frontend production build: passed after the UI fix. +- TypeScript check (`npx tsc --noEmit`): passed after the UI fix. +- Focused subscription and model factory tests rerun after browser validation: **23 passed**. +- Python lint, formatting and whitespace checks: passed. +- Combined subscription, model factory, golden-payload and reasoning regression run: **850 passed, 1 failed**. The failing test is `tests/llm/golden/test_golden_payloads.py::test_provider_request_quirks`, which expects an `omniroute` provider absent from the registry. The same failure was reproduced while loading the changed Python modules from `HEAD`, confirming it predates this feature. + +## Screenshots + +### 1. Anthropic onboarding offers subscription sign-in + +![Claude subscription sign-in during onboarding](validation/claude-code/01-onboarding-sign-in.jpg) + +### 2. Connected during onboarding without an API key + +![Connected Claude subscription in onboarding](validation/claude-code/02-onboarding-connected.jpg) + +### 3. Connected in settings with Test Connection enabled + +![Connected subscription and enabled Test Connection](validation/claude-code/04-settings-connected.jpg) + +### 4. Real inference error is visible + +![Claude organization access error](validation/claude-code/05-live-inference-error.jpg) + +### 5. Saved model persists after reload + +![Saved Haiku model and connected subscription](validation/claude-code/06-saved-model-after-reload.jpg) + +### 6. Disconnect restores the API-key alternative + +![Disconnected subscription with API-key entry](validation/claude-code/07-settings-disconnected.jpg) + +## Manual acceptance + +1. Open the running instance and go to **Settings → Model**. Confirm Anthropic, Connected, the selected models and an enabled Test Connection button. +2. Resolve Claude Code's account-access error, using `claude auth login` if appropriate or contacting the organization's administrator. Login must complete in Anthropic's own flow. +3. Return to CraftBot and run **Test Connection**. Successful inference still needs to be confirmed after account access is restored. +4. Optionally disconnect and reconnect to confirm the API-key alternative and subscription toggle behavior. + +These earlier checks are historical. Use Current manual acceptance above to validate the private-profile implementation. diff --git a/docs/validation/claude-code/01-onboarding-sign-in.jpg b/docs/validation/claude-code/01-onboarding-sign-in.jpg new file mode 100644 index 00000000..5f3d4d78 Binary files /dev/null and b/docs/validation/claude-code/01-onboarding-sign-in.jpg differ diff --git a/docs/validation/claude-code/02-onboarding-connected.jpg b/docs/validation/claude-code/02-onboarding-connected.jpg new file mode 100644 index 00000000..76d4d745 Binary files /dev/null and b/docs/validation/claude-code/02-onboarding-connected.jpg differ diff --git a/docs/validation/claude-code/04-settings-connected.jpg b/docs/validation/claude-code/04-settings-connected.jpg new file mode 100644 index 00000000..25d5c87e Binary files /dev/null and b/docs/validation/claude-code/04-settings-connected.jpg differ diff --git a/docs/validation/claude-code/05-live-inference-error.jpg b/docs/validation/claude-code/05-live-inference-error.jpg new file mode 100644 index 00000000..5345ce27 Binary files /dev/null and b/docs/validation/claude-code/05-live-inference-error.jpg differ diff --git a/docs/validation/claude-code/06-saved-model-after-reload.jpg b/docs/validation/claude-code/06-saved-model-after-reload.jpg new file mode 100644 index 00000000..ea56eca0 Binary files /dev/null and b/docs/validation/claude-code/06-saved-model-after-reload.jpg differ diff --git a/docs/validation/claude-code/07-settings-disconnected.jpg b/docs/validation/claude-code/07-settings-disconnected.jpg new file mode 100644 index 00000000..d1daffd4 Binary files /dev/null and b/docs/validation/claude-code/07-settings-disconnected.jpg differ diff --git a/docs/validation/claude-code/08-independent-profile.jpg b/docs/validation/claude-code/08-independent-profile.jpg new file mode 100644 index 00000000..69608c15 Binary files /dev/null and b/docs/validation/claude-code/08-independent-profile.jpg differ diff --git a/docs/validation/claude-code/09-private-profile-before-connect.jpg b/docs/validation/claude-code/09-private-profile-before-connect.jpg new file mode 100644 index 00000000..69608c15 Binary files /dev/null and b/docs/validation/claude-code/09-private-profile-before-connect.jpg differ diff --git a/docs/validation/claude-code/10-private-profile-login-pending.jpg b/docs/validation/claude-code/10-private-profile-login-pending.jpg new file mode 100644 index 00000000..163da981 Binary files /dev/null and b/docs/validation/claude-code/10-private-profile-login-pending.jpg differ diff --git a/tests/integrations/test_claude_code_subscription.py b/tests/integrations/test_claude_code_subscription.py new file mode 100644 index 00000000..ba186af1 --- /dev/null +++ b/tests/integrations/test_claude_code_subscription.py @@ -0,0 +1,1025 @@ +"""Claude subscription routing must never export OAuth tokens or bill an API key.""" + +import asyncio +import json +import queue +import subprocess +import threading +import webbrowser +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from craftos_integrations.config import ConfigStore +from craftos_integrations.llm_oauth import claude_code, tokens +from agent_core.core.models.claude_code_client import ClaudeCodeClient +from agent_core.core.models.factory import ModelFactory +from agent_core.core.models.types import InterfaceType + + +@pytest.fixture(autouse=True) +def isolated_connection(tmp_path, monkeypatch): + monkeypatch.setattr(ConfigStore, "project_root", tmp_path) + monkeypatch.setattr(claude_code, "_login_process", None) + monkeypatch.setattr(claude_code, "_login_generation", 0) + # Never find the real CLI installed on the test machine. + monkeypatch.setattr(claude_code, "_native_install", lambda: tmp_path / "no-claude") + + +@pytest.fixture(autouse=True) +def opened(monkeypatch): + pages = [] + monkeypatch.setattr(webbrowser, "open", pages.append) + return pages + + +class FakeLogin: + """`claude auth login` without a terminal: opens its own browser tab and + exits once the user approves there, with one code exchange.""" + + def __init__(self, args, *, env, outcome="approve", on_success=None, **kwargs): + self.args, self.env, self.on_success = args, env, on_success + self.lines = queue.Queue() + self.received = [] + self.returncode = None + self.exited = threading.Event() + self.stdout = SimpleNamespace(readline=self.lines.get) + self.stdin = SimpleNamespace(write=self.received.append, flush=lambda: None) + self.lines.put(b"Opening browser to sign in\n") + if outcome == "approve": + threading.Timer(0.05, self._approve).start() + elif outcome == "reject": + threading.Timer(0.05, self._reject).start() + + def _approve(self): + if self.on_success: + self.on_success() + self._exit(0, "Login successful.") + + def _reject(self): + self._exit( + 1, + "Paste code here if prompted > Login failed: " + "Request failed with status code 400", + ) + + def _exit(self, code, line): + if self.returncode is not None: + return + self.lines.put(line.encode() + b"\n") + self.lines.put(b"") + self.returncode = code + self.exited.set() + + def poll(self): + return self.returncode + + def wait(self, timeout=None): + if not self.exited.wait(timeout): + raise subprocess.TimeoutExpired("claude", timeout) + return self.returncode + + def kill(self): + self._exit(1, "") + + +def fake_cli(monkeypatch, **behaviour): + launched = [] + + def popen(args, **kwargs): + launched.append(FakeLogin(args, **kwargs, **behaviour)) + return launched[-1] + + monkeypatch.setattr(claude_code, "cli_command", lambda: ["claude"]) + monkeypatch.setattr(claude_code.subprocess, "Popen", popen) + return launched + + +def claude_account(monkeypatch): + """A private profile that is signed out until the CLI's tab is approved. + Returns the hook that signs it in.""" + state = {"signed_in": False} + monkeypatch.setattr( + claude_code, + "auth_status", + lambda: ( + {"connected": True, "email": "user@example.com", "plan": "max"} + if state["signed_in"] + else {"connected": False, "error": "Use Connect"} + ), + ) + return lambda: state.update(signed_in=True) + + +def connected(monkeypatch): + def signed_out_cli(args, **kwargs): + assert args in (["auth", "logout"], ["auth", "status"]) + return SimpleNamespace(returncode=0, stdout='{"loggedIn": false}') + + monkeypatch.setattr(claude_code, "run_cli", signed_out_cli) + monkeypatch.setattr( + claude_code, + "auth_status", + lambda: { + "connected": True, + "email": "user@example.com", + "plan": "max", + }, + ) + assert asyncio.run(tokens.connect("anthropic"))[0] + + +def test_connection_is_explicit_and_does_not_store_cli_credentials( + monkeypatch, tmp_path +): + assert not tokens.has_credential("anthropic") + assert tokens.status("anthropic") == {"supported": True, "connected": False} + connected(monkeypatch) + assert tokens.has_credential("anthropic") + assert tokens.status("anthropic")["email"] == "user@example.com" + assert tokens.get_bearer("anthropic") is None + assert json.loads( + (tmp_path / ".credentials" / claude_code.CRED_FILE).read_text() + ) == { + "enabled": True, + "profile_version": claude_code.PROFILE_VERSION, + } + + +def test_disconnect_logs_out_then_verifies_before_clearing_marker(monkeypatch): + connected(monkeypatch) + calls = [] + + def logout(args, **kwargs): + assert tokens.has_credential("anthropic") + calls.append(args) + return SimpleNamespace(returncode=0, stdout='{"loggedIn": false}') + + monkeypatch.setattr(claude_code, "run_cli", logout) + assert tokens.disconnect("anthropic")[0] + assert calls == [["auth", "logout"], ["auth", "status"]] + assert not tokens.has_credential("anthropic") + + +@pytest.mark.parametrize( + "method", ["api_key", "api_key_helper", "third_party", "oauth_token"] +) +def test_auth_status_rejects_non_subscription_auth(monkeypatch, method): + monkeypatch.setattr( + claude_code, + "run_cli", + lambda *a, **k: SimpleNamespace( + returncode=0, + stdout=json.dumps({"loggedIn": True, "authMethod": method}), + ), + ) + assert not claude_code.auth_status()["connected"] + + +def test_connect_adopts_an_existing_private_sign_in_without_a_browser(monkeypatch): + monkeypatch.setattr( + claude_code, "auth_status", lambda: {"connected": True, "email": "a@b.c"} + ) + monkeypatch.setattr( + claude_code.subprocess, "Popen", lambda *a, **k: pytest.fail("No login") + ) + assert asyncio.run(tokens.connect("anthropic"))[0] + assert tokens.has_credential("anthropic") + + +def test_connect_waits_for_approval_in_the_cli_tab(monkeypatch, opened): + launched = fake_cli(monkeypatch, on_success=claude_account(monkeypatch)) + ok, message = asyncio.run(tokens.connect("anthropic")) + assert ok and "user@example.com" in message + login = launched[0] + assert login.args == ["claude", "auth", "login"] + assert login.env["CLAUDE_CONFIG_DIR"] == str(claude_code.profile_directory()) + # The CLI opens the only tab, and no code passes through CraftBot. + assert opened == [] and login.received == [] + assert tokens.has_credential("anthropic") + + +def test_failed_approval_is_reported_and_does_not_connect(monkeypatch): + claude_account(monkeypatch) + fake_cli(monkeypatch, outcome="reject") + ok, message = asyncio.run(tokens.connect("anthropic")) + assert not ok and "Login failed: Request failed" in message + assert "Paste code here" not in message + assert not tokens.has_credential("anthropic") + + +def test_abandoned_sign_in_times_out(monkeypatch): + claude_account(monkeypatch) + launched = fake_cli(monkeypatch, outcome="abandon") + monkeypatch.setattr(claude_code, "LOGIN_TIMEOUT_SECONDS", 0.2) + ok, message = asyncio.run(tokens.connect("anthropic")) + assert not ok and "timed out" in message + assert launched[0].returncode is not None + assert not tokens.has_credential("anthropic") + + +def test_new_connect_replaces_an_abandoned_sign_in(monkeypatch): + signed_in = claude_account(monkeypatch) + outcomes = iter(["abandon", "approve"]) + launched = [] + + def popen(args, **kwargs): + launched.append( + FakeLogin(args, **kwargs, outcome=next(outcomes), on_success=signed_in) + ) + return launched[-1] + + monkeypatch.setattr(claude_code, "cli_command", lambda: ["claude"]) + monkeypatch.setattr(claude_code.subprocess, "Popen", popen) + with ThreadPoolExecutor() as pool: + first = pool.submit(asyncio.run, tokens.connect("anthropic")) + while claude_code._login_process is None: + threading.Event().wait(0.01) + ok, _ = asyncio.run(tokens.connect("anthropic")) + assert ok + ok, message = first.result(timeout=5) + assert not ok and "replaced" in message + assert tokens.has_credential("anthropic") + + +def test_cli_that_cannot_start_says_why(monkeypatch): + claude_account(monkeypatch) + monkeypatch.setattr(claude_code, "cli_command", lambda: ["claude"]) + + def blocked(*args, **kwargs): + raise OSError("blocked by policy") + + monkeypatch.setattr(claude_code.subprocess, "Popen", blocked) + ok, message = asyncio.run(tokens.connect("anthropic")) + assert not ok and "blocked by policy" in message + + +def test_settings_connect_button_flips_to_connected(monkeypatch): + from app.ui_layer.adapters.browser_adapter import BrowserAdapter + from app.ui_layer.settings import provider_settings + + fake_cli(monkeypatch, on_success=claude_account(monkeypatch)) + modes = [] + monkeypatch.setattr( + provider_settings, "_persist_auth_mode", lambda *args: modes.append(args) + ) + adapter = object.__new__(BrowserAdapter) + sent = [] + + async def broadcast(message): + sent.append(message) + + adapter._broadcast = broadcast + + async def activate(ok, provider, **kwargs): + return provider if ok else None + + adapter._activate_provider_via_settings = activate + asyncio.run(adapter._handle_model_subscription_connect("anthropic")) + assert [m["type"] for m in sent] == ["model_subscription_connect"] + result = sent[0]["data"] + assert result["success"] and result["active_provider"] == "anthropic" + assert result["status"]["connected"] + assert modes == [("anthropic", "subscription")] + + +def test_inherited_api_auth_and_nested_session_do_not_override_subscription( + monkeypatch, +): + for name in ( + "ANTHROPIC_API_KEY", + "ANTHROPIC_AUTH_TOKEN", + "ANTHROPIC_BASE_URL", + "CLAUDE_CODE_OAUTH_TOKEN", + "CLAUDE_CODE_USE_BEDROCK", + "CLAUDECODE", + "MAX_THINKING_TOKENS", + "CLAUDE_CODE_EFFORT_LEVEL", + "CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING", + ): + monkeypatch.setenv(name, "must-not-reach-cli") + monkeypatch.setenv("CLAUDE_CONFIG_DIR", "/my/claude/config") + env = claude_code.cli_environment() + assert "must-not-reach-cli" not in env.values() + assert env["CLAUDE_CONFIG_DIR"] == str(claude_code.profile_directory()) + assert env["CLAUDE_CONFIG_DIR"] != "/my/claude/config" + assert claude_code.os.environ["CLAUDE_CONFIG_DIR"] == "/my/claude/config" + + +def test_factory_uses_cli_before_api_key_and_reverts_after_disconnect(monkeypatch): + connected(monkeypatch) + ctx = ModelFactory.create( + provider="anthropic", interface=InterfaceType.LLM, api_key="paid-key" + ) + assert isinstance(ctx["anthropic_client"], ClaudeCodeClient) + assert ctx["auth_mode"] == "subscription" + tokens.disconnect("anthropic") + client = object() + monkeypatch.setattr( + "agent_core.core.models.factory._create_anthropic_client", lambda **k: client + ) + ctx = ModelFactory.create( + provider="anthropic", interface=InterfaceType.LLM, api_key="paid-key" + ) + assert ctx["anthropic_client"] is client + assert "auth_mode" not in ctx + + +def test_request_preserves_text_images_and_usage_without_running_tools(monkeypatch): + connected(monkeypatch) + prompt = "system instructions " * 10000 + image = { + "type": "image", + "source": {"type": "base64", "media_type": "image/png", "data": "abc"}, + } + temporary_paths = [] + + def run(args, **kwargs): + assert "--tools" in args and args[args.index("--tools") + 1] == "" + assert "--strict-mcp-config" in args + assert "--no-session-persistence" in args + assert Path(args[args.index("--system-prompt-file") + 1]).read_text() == prompt + settings = Path(args[args.index("--settings") + 1]) + assert json.loads(settings.read_text())["disableAllHooks"] + assert json.loads(Path(args[args.index("--mcp-config") + 1]).read_text()) == { + "mcpServers": {} + } + temporary_paths.append(settings.parent) + blocks = json.loads(kwargs["input"])["message"]["content"] + assert image in blocks + texts = " ".join(b.get("text", "") for b in blocks) + assert ( + "earlier question" in texts + and "earlier answer" in texts + and "latest question" in texts + ) + assert "[assistant]" in texts + assert kwargs["env_overrides"]["CLAUDE_CODE_MAX_OUTPUT_TOKENS"] == "123" + return SimpleNamespace( + returncode=0, + stdout=json.dumps( + { + "type": "result", + "is_error": False, + "result": "answer", + "usage": { + "input_tokens": 20, + "output_tokens": 5, + "cache_read_input_tokens": 10, + }, + } + ), + ) + + monkeypatch.setattr(claude_code, "run_cli", run) + result = ClaudeCodeClient().messages.create( + model="claude-sonnet-4-6", + max_tokens=123, + system=[ + {"type": "text", "text": prompt, "cache_control": {"type": "ephemeral"}} + ], + messages=[ + {"role": "user", "content": "earlier question"}, + {"role": "assistant", "content": "earlier answer"}, + { + "role": "user", + "content": [image, {"type": "text", "text": "latest question"}], + }, + ], + ) + assert result.content[0].text == "answer" + assert result.usage.input_tokens == 20 + assert result.usage.cache_read_input_tokens == 10 + assert all(not path.exists() for path in temporary_paths) + + +@pytest.mark.parametrize( + "stdout,code", + [ + ("not json", 1), + (json.dumps({"type": "result", "is_error": True, "result": "rate limited"}), 0), + ], +) +def test_cli_failure_is_not_silently_billed_to_api_key(monkeypatch, stdout, code): + connected(monkeypatch) + monkeypatch.setattr( + claude_code, + "run_cli", + lambda *a, **k: SimpleNamespace(returncode=code, stdout=stdout), + ) + with pytest.raises(RuntimeError, match="Claude Code"): + ClaudeCodeClient().create( + model="sonnet", messages=[{"role": "user", "content": "hi"}] + ) + + +def test_existing_client_stops_after_disconnect(monkeypatch): + connected(monkeypatch) + client = ClaudeCodeClient() + tokens.disconnect("anthropic") + monkeypatch.setattr( + claude_code, "run_cli", lambda *a, **k: pytest.fail("Disconnected") + ) + with pytest.raises(RuntimeError, match="disconnected"): + client.create(model="sonnet", messages=[{"role": "user", "content": "hi"}]) + + +def test_settings_allow_connected_claude_without_api_key(monkeypatch): + from app.ui_layer.settings import model_settings + + monkeypatch.setattr(model_settings, "_load_settings", lambda: {}) + assert not model_settings.validate_can_save("anthropic")["success"] + connected(monkeypatch) + assert model_settings.validate_can_save("anthropic")["success"] + info = next( + p + for p in model_settings.get_available_providers()["providers"] + if p["id"] == "anthropic" + ) + assert info["supports_subscription_oauth"] + assert info["subscription_label"] == "Sign in with Claude" + from app.onboarding.interfaces.steps import ApiKeyStep + + assert ApiKeyStep("anthropic").subscription_label() == "Sign in with Claude" + + +def test_connection_test_uses_selected_cli_model(monkeypatch): + from agent_core.core.models.connection_tester import test_provider_connection + + connected(monkeypatch) + calls = [] + monkeypatch.setattr( + ClaudeCodeClient, "create", lambda self, **kwargs: calls.append(kwargs) + ) + result = test_provider_connection( + "anthropic", api_key="unused-paid-key", model="claude-sonnet-4-6" + ) + assert result["success"] + assert calls[0]["model"] == "claude-sonnet-4-6" + + +def test_windows_npm_cli_bypasses_shell(monkeypatch, tmp_path): + shim = tmp_path / "claude.cmd" + entry = tmp_path / "node_modules/@anthropic-ai/claude-code/cli.js" + entry.parent.mkdir(parents=True) + entry.write_text("// official CLI entrypoint") + monkeypatch.setattr( + claude_code.shutil, + "which", + lambda name: str(shim) if name == "claude" else "node.exe", + ) + assert claude_code.cli_command() == ["node.exe", str(entry)] + + +def test_missing_cli_has_install_instructions(monkeypatch): + monkeypatch.setattr(claude_code.shutil, "which", lambda name: None) + success, message = asyncio.run(tokens.connect("anthropic")) + assert not success and "Install" in message + + +def test_native_install_is_used_when_app_path_is_stale(monkeypatch, tmp_path): + native = tmp_path / "claude.exe" + native.write_text("") + monkeypatch.setattr(claude_code.shutil, "which", lambda name: None) + monkeypatch.setattr(claude_code, "_native_install", lambda: native) + assert claude_code.cli_command() == [str(native)] + + +def test_status_detects_cli_logout_without_exporting_tokens(monkeypatch): + connected(monkeypatch) + monkeypatch.setattr( + claude_code, + "auth_status", + lambda: {"connected": False, "error": "Sign in again"}, + ) + assert not tokens.status("anthropic")["connected"] + assert tokens.status("anthropic")["configured"] + assert tokens.get_bearer("anthropic") is None + + +def test_invalid_login_can_disconnect_before_switching_to_an_api_key(monkeypatch): + from app.ui_layer.settings import provider_settings + from agent_core.core.models import connection_tester + + connected(monkeypatch) + monkeypatch.setattr( + claude_code, + "auth_status", + lambda: {"connected": False, "error": "Sign in again"}, + ) + monkeypatch.setattr(provider_settings, "_persist_auth_mode", lambda *args: None) + assert tokens.status("anthropic") == { + "supported": True, + "configured": True, + "connected": False, + "error": "Sign in again", + } + # A failed login never silently selects the paid API key. + context = ModelFactory.create( + provider="anthropic", interface=InterfaceType.LLM, api_key="paid-key" + ) + assert isinstance(context["anthropic_client"], ClaudeCodeClient) + # Disconnect still verifies the already-logged-out CLI before clearing opt-in. + assert provider_settings.disconnect_subscription("anthropic")[0] + assert tokens.status("anthropic") == {"supported": True, "connected": False} + api_client = object() + monkeypatch.setattr( + "agent_core.core.models.factory._create_anthropic_client", + lambda **kwargs: api_client, + ) + context = ModelFactory.create( + provider="anthropic", interface=InterfaceType.LLM, api_key="paid-key" + ) + assert context["anthropic_client"] is api_client + tested = [] + monkeypatch.setattr( + connection_tester, + "_test_anthropic", + lambda key, *args: tested.append(key) or {"success": True}, + ) + assert connection_tester.test_provider_connection("anthropic", api_key="paid-key")[ + "success" + ] + assert tested == ["paid-key"] + + +def test_failed_logout_verification_keeps_disconnect_available(monkeypatch): + read_status = claude_code.auth_status + connected(monkeypatch) + monkeypatch.setattr(claude_code, "auth_status", read_status) + monkeypatch.setattr( + claude_code, + "run_cli", + lambda *args, **kwargs: SimpleNamespace(returncode=0, stdout="invalid status"), + ) + assert not tokens.disconnect("anthropic")[0] + status = tokens.status("anthropic") + assert not status["connected"] + assert status["configured"] and status["error"] + # A subsequent successful retry clears both routing and recovery state. + monkeypatch.setattr( + claude_code, + "run_cli", + lambda *args, **kwargs: SimpleNamespace( + returncode=0, stdout='{"loggedIn": false}' + ), + ) + assert tokens.disconnect("anthropic")[0] + assert tokens.status("anthropic") == {"supported": True, "connected": False} + + +def test_old_shared_login_marker_requires_new_profile_sign_in(tmp_path): + from craftos_integrations.credentials_store import save_credential + + save_credential(claude_code.CRED_FILE, claude_code.ClaudeCodeConnection()) + assert not tokens.has_credential("anthropic") + assert tokens.status("anthropic") == {"supported": True, "connected": False} + assert not (tmp_path / ".credentials" / "claude_code").exists() + + +def test_all_cli_commands_force_same_private_profile(monkeypatch): + monkeypatch.setenv("CLAUDE_CONFIG_DIR", "/standalone/profile") + monkeypatch.setattr(claude_code, "cli_command", lambda: ["claude"]) + invocations = [] + + def subprocess_run(args, **kwargs): + invocations.append((args, kwargs["env"]["CLAUDE_CONFIG_DIR"])) + return SimpleNamespace(returncode=0, stdout='{"loggedIn": false}') + + monkeypatch.setattr(claude_code.subprocess, "run", subprocess_run) + for args in ( + ["auth", "login"], + ["auth", "status"], + ["auth", "logout"], + ["--print"], + ): + claude_code.run_cli( + args, timeout=10, env_overrides={"CLAUDE_CONFIG_DIR": "/wrong/profile"} + ) + assert len(invocations) == 4 + assert {path for _, path in invocations} == {str(claude_code.profile_directory())} + assert claude_code.os.environ["CLAUDE_CONFIG_DIR"] == "/standalone/profile" + + +def test_profiles_are_scoped_to_craftbot_installation(monkeypatch, tmp_path): + first = claude_code.profile_directory() + monkeypatch.setattr(ConfigStore, "project_root", tmp_path / "another-installation") + assert claude_code.profile_directory() != first + + +@pytest.mark.parametrize( + "failure", ["exit", "timeout", "still_logged_in", "invalid_status"] +) +def test_failed_logout_keeps_connection_and_auth_mode(monkeypatch, failure): + from app.ui_layer.settings import provider_settings + + connected(monkeypatch) + modes = [] + monkeypatch.setattr( + provider_settings, "_persist_auth_mode", lambda *args: modes.append(args) + ) + + def fail(args, **kwargs): + if args == ["auth", "logout"]: + if failure == "timeout": + raise subprocess.TimeoutExpired("claude", 30) + return SimpleNamespace(returncode=1 if failure == "exit" else 0) + return SimpleNamespace( + returncode=0, + stdout='{"loggedIn": true}' if failure == "still_logged_in" else "invalid", + ) + + monkeypatch.setattr(claude_code, "run_cli", fail) + success, message = provider_settings.disconnect_subscription("anthropic") + assert not success and message + assert tokens.has_credential("anthropic") + assert modes == [] + + +def test_reconnect_after_logout_needs_a_new_sign_in(monkeypatch): + logged_in = False + + def signed_in(): + nonlocal logged_in + logged_in = True + + def cli(args, **kwargs): + nonlocal logged_in + if args == ["auth", "logout"]: + logged_in = False + return SimpleNamespace( + returncode=0, + stdout=json.dumps({"loggedIn": logged_in, "authMethod": "claude.ai"}), + ) + + launched = fake_cli(monkeypatch, on_success=signed_in) + monkeypatch.setattr(claude_code, "run_cli", cli) + for _ in range(2): + assert asyncio.run(tokens.connect("anthropic"))[0] + assert tokens.disconnect("anthropic")[0] + assert not tokens.has_credential("anthropic") + assert len(launched) == 2 + + +@pytest.mark.parametrize( + "model,choice,expected_budget,expected_effort", + [ + ("claude-sonnet-4-6", "off", "0", None), + ("claude-sonnet-4-6", "provider_default", "0", None), + ("claude-sonnet-4-6", "high", None, "high"), + ("claude-haiku-4-5-20251001", "off", "0", None), + ("claude-haiku-4-5-20251001", "provider_default", "0", None), + ("claude-haiku-4-5-20251001", "high", "12288", None), + ("claude-sonnet-5", "off", "0", None), + ("claude-sonnet-5", "provider_default", None, None), + ("claude-sonnet-5-5", "provider_default", None, None), + ], +) +def test_cli_honors_transport_reasoning_choices( + monkeypatch, model, choice, expected_budget, expected_effort +): + from agent_core.core.impl.llm.reasoning_wire import for_anthropic + from agent_core.core.models.reasoning import ReasoningChoice, resolve_reasoning + + run_cli = claude_code.run_cli + connected(monkeypatch) + monkeypatch.setattr(claude_code, "run_cli", run_cli) + # Standalone CLI preferences must not override this request's choice. + monkeypatch.setenv("MAX_THINKING_TOKENS", "0") + monkeypatch.setenv("CLAUDE_CODE_EFFORT_LEVEL", "low") + monkeypatch.setenv("CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING", "1") + monkeypatch.setattr(claude_code, "cli_command", lambda: ["claude"]) + calls = [] + + def run(args, **kwargs): + calls.append((args, kwargs["env"])) + return SimpleNamespace( + returncode=0, + stdout=json.dumps({"type": "result", "result": "OK"}), + ) + + monkeypatch.setattr(claude_code.subprocess, "run", run) + applied = for_anthropic( + resolve_reasoning("anthropic", model, "subscription", ReasoningChoice(choice)), + 16384, + ) + ClaudeCodeClient().create( + model=model, + messages=[{"role": "user", "content": "hi"}], + max_tokens=applied.output_cap, + **applied.fields, + ) + args, env = calls[0] + assert env.get("MAX_THINKING_TOKENS") == expected_budget + assert "CLAUDE_CODE_EFFORT_LEVEL" not in env + assert "CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING" not in env + effort = args[args.index("--effort") + 1] if "--effort" in args else None + assert effort == expected_effort + + +@pytest.mark.parametrize( + "operation", + [ + "get", + "save", + "image_rollback", + "video_rollback", + "connect", + "complete", + "ollama", + "pull", + ], +) +def test_browser_subscription_checks_run_off_the_event_loop(monkeypatch, operation): + from app.ui_layer.adapters import browser_adapter + from app.ui_layer.settings import model_settings + from app.ui_layer import local_llm_setup + + connected(monkeypatch) + status_threads = [] + reinit_threads = [] + sent = [] + + def status(): + status_threads.append(threading.get_ident()) + return {"connected": True} + + def reinitialize(provider): + reinit_threads.append(threading.get_ident()) + return True + + async def broadcast(message): + sent.append(message) + + async def connect(provider): + return True, "Connected" + + async def pull(*args, **kwargs): + return {"success": True} + + monkeypatch.setattr(claude_code, "auth_status", status) + monkeypatch.setattr(model_settings, "_load_settings", lambda: {}) + monkeypatch.setattr(model_settings, "_save_settings", lambda settings: True) + monkeypatch.setattr("app.config.reload_settings", lambda: None) + monkeypatch.setattr("app.config.get_image_gen_provider", lambda: "openai") + monkeypatch.setattr("app.config.get_image_gen_model", lambda: None) + monkeypatch.setattr("app.config.get_video_gen_provider", lambda: "gemini") + monkeypatch.setattr("app.config.get_video_gen_model", lambda: None) + monkeypatch.setattr(browser_adapter, "connect_subscription_async", connect) + monkeypatch.setattr( + browser_adapter, "complete_subscription", lambda *args: (True, "Connected") + ) + monkeypatch.setattr( + browser_adapter, + "get_ollama_models", + lambda **kwargs: {"success": True, "models": []}, + ) + monkeypatch.setattr(local_llm_setup, "pull_ollama_model", pull) + adapter = object.__new__(browser_adapter.BrowserAdapter) + adapter._broadcast = broadcast + adapter._controller = SimpleNamespace( + agent=SimpleNamespace( + reinitialize_llm=reinitialize, + reinitialize_image_gen=lambda provider: False, + reinitialize_video_gen=lambda provider: False, + ) + ) + + async def run(): + loop_thread = threading.get_ident() + if operation == "get": + await adapter._handle_model_settings_get() + elif operation == "save": + await adapter._handle_model_settings_update( + {"llmModel": "claude-sonnet-4-6"} + ) + elif operation == "image_rollback": + await adapter._handle_model_settings_update({"imageGenProvider": "openai"}) + elif operation == "video_rollback": + await adapter._handle_model_settings_update({"videoGenProvider": "gemini"}) + elif operation == "connect": + await adapter._handle_model_subscription_connect("anthropic") + elif operation == "complete": + await adapter._handle_model_subscription_complete("anthropic", "code", None) + elif operation == "ollama": + await adapter._handle_ollama_models_get() + elif operation == "pull": + await adapter._handle_local_llm_pull_model("test-model") + assert status_threads + assert all(thread != loop_thread for thread in status_threads) + assert all(thread == loop_thread for thread in reinit_threads) + + asyncio.run(run()) + assert sent[-1]["data"]["success"] + if operation in ("image_rollback", "video_rollback"): + assert len(status_threads) == 1 + assert sent[-1]["data"]["warning"] + elif operation in ("connect", "complete"): + assert sent[-1]["data"]["active_provider"] == "anthropic" + assert len(reinit_threads) == 1 + + +def test_onboarding_uses_saved_connection_without_a_cli_status_check(monkeypatch): + from app.onboarding.interfaces.steps import ApiKeyStep + from app.ui_layer.onboarding.controller import OnboardingFlowController + + connected(monkeypatch) + monkeypatch.setattr( + claude_code, + "auth_status", + lambda: pytest.fail("Blocking CLI status in onboarding"), + ) + assert ApiKeyStep("anthropic").validate("") == (True, None) + assert OnboardingFlowController._subscription_connected("anthropic") + monkeypatch.setattr(claude_code, "has_credential", lambda: False) + assert not ApiKeyStep("anthropic").validate("")[0] + assert not OnboardingFlowController._subscription_connected("anthropic") + + +def test_onboarding_settings_updates_can_skip_unused_live_status(monkeypatch): + from app.ui_layer.settings import model_settings + + connected(monkeypatch) + monkeypatch.setattr(model_settings, "_load_settings", lambda: {}) + monkeypatch.setattr(model_settings, "_save_settings", lambda settings: True) + monkeypatch.setattr("app.config.reload_settings", lambda: None) + monkeypatch.setattr( + claude_code, + "auth_status", + lambda: pytest.fail("Unused CLI status in onboarding"), + ) + result = model_settings.update_model_settings( + image_gen_provider="openai", include_subscription_status=False + ) + assert result["success"] + assert result["image_gen_provider"] == "openai" + + +@pytest.mark.parametrize( + "checkpoint", ["existing_login", "browser_wait", "approved_login"] +) +def test_disconnect_invalidates_every_login_phase(monkeypatch, checkpoint): + """Disconnect wins even after CLI exit or an existing-account status read.""" + from craftos_integrations.credentials_store import save_credential + + save_credential( + claude_code.CRED_FILE, + claude_code.ClaudeCodeConnection(profile_version=claude_code.PROFILE_VERSION), + ) + reached = threading.Event() + release = threading.Event() + calls = 0 + launched = [] + + def auth_status(): + nonlocal calls + calls += 1 + current = {"connected": checkpoint == "existing_login" or calls > 1} + if checkpoint == "existing_login" or calls > 1: + reached.set() + assert release.wait(5) + return current + + def popen(args, **kwargs): + process = FakeLogin(args, **kwargs, outcome="abandon") + launched.append(process) + reached.set() + return process + + monkeypatch.setattr(claude_code, "auth_status", auth_status) + monkeypatch.setattr(claude_code, "cli_command", lambda: ["claude"]) + monkeypatch.setattr(claude_code.subprocess, "Popen", popen) + + def logout(args, **kwargs): + assert all(process.poll() is not None for process in launched) + return SimpleNamespace(returncode=0, stdout='{"loggedIn": false}') + + monkeypatch.setattr(claude_code, "run_cli", logout) + with ThreadPoolExecutor() as pool: + login = pool.submit(asyncio.run, tokens.connect("anthropic")) + try: + assert reached.wait(5) + if checkpoint == "approved_login": + reached.clear() + launched[0]._approve() + assert reached.wait(5) + assert tokens.disconnect("anthropic")[0] + assert not tokens.has_credential("anthropic") + finally: + release.set() + assert not login.result(timeout=5)[0] + assert not tokens.has_credential("anthropic") + assert claude_code._login_process is None + + +def test_disconnect_waits_for_pending_cli_exit_before_logout(monkeypatch): + """Do not report success while a process can still write private auth.""" + connected(monkeypatch) + process = SimpleNamespace(poll=lambda: None, kill=lambda: None) + + def stuck(timeout): + raise subprocess.TimeoutExpired("claude", timeout) + + process.wait = stuck + monkeypatch.setattr(claude_code, "_login_process", process) + monkeypatch.setattr( + claude_code, "run_cli", lambda *args, **kwargs: pytest.fail("CLI still running") + ) + assert not tokens.disconnect("anthropic")[0] + assert tokens.has_credential("anthropic") + + +def test_browser_disconnect_cancels_pending_login_and_reconnects_cleanly( + monkeypatch, tmp_path +): + """Full backend workflow: real handlers, auth facade, settings and factory.""" + from app import config + from app.ui_layer.adapters.browser_adapter import BrowserAdapter + from app.ui_layer.settings import model_settings, provider_settings + from craftos_integrations.credentials_store import save_credential + + path = tmp_path / "settings.json" + path.write_text(json.dumps({"model": {"llm_provider": "anthropic"}})) + for module in (config, model_settings, provider_settings): + monkeypatch.setattr(module, "SETTINGS_CONFIG_PATH", path) + monkeypatch.setattr(config, "_settings_cache", None) + save_credential( + claude_code.CRED_FILE, + claude_code.ClaudeCodeConnection(profile_version=claude_code.PROFILE_VERSION), + ) + state = {"loggedIn": False, "authMethod": "claude.ai"} + started = threading.Event() + launched = [] + outcomes = iter(["abandon", "approve"]) + + def signed_in(): + state["loggedIn"] = True + + def popen(args, **kwargs): + process = FakeLogin( + args, **kwargs, outcome=next(outcomes), on_success=signed_in + ) + launched.append(process) + started.set() + return process + + def cli(args, **kwargs): + if args == ["auth", "logout"]: + state["loggedIn"] = False + return SimpleNamespace(returncode=0, stdout=json.dumps(state)) + + monkeypatch.setattr(claude_code, "cli_command", lambda: ["claude"]) + monkeypatch.setattr(claude_code.subprocess, "Popen", popen) + monkeypatch.setattr(claude_code, "run_cli", cli) + api_client = object() + monkeypatch.setattr( + "agent_core.core.models.factory._create_anthropic_client", + lambda **kwargs: api_client, + ) + clients = [] + sent = [] + + def reinitialize(provider): + context = ModelFactory.create( + provider=provider, interface=InterfaceType.LLM, api_key="paid-key" + ) + clients.append(context["anthropic_client"]) + + async def broadcast(message): + sent.append(message) + + adapter = object.__new__(BrowserAdapter) + adapter._broadcast = broadcast + adapter._controller = SimpleNamespace( + agent=SimpleNamespace(reinitialize_llm=reinitialize) + ) + + async def run(): + pending = asyncio.create_task( + adapter._handle_model_subscription_connect("anthropic") + ) + assert await asyncio.to_thread(started.wait, 5) + await adapter._handle_model_subscription_disconnect("anthropic") + await pending + assert not tokens.has_credential("anthropic") + assert clients == [api_client] + assert json.loads(path.read_text())["auth_mode"]["anthropic"] == "api_key" + assert not next( + message + for message in sent + if message["type"] == "model_subscription_connect" + )["data"]["success"] + await adapter._handle_model_subscription_connect("anthropic") + assert isinstance(clients[-1], ClaudeCodeClient) + assert tokens.has_credential("anthropic") + assert json.loads(path.read_text())["auth_mode"]["anthropic"] == "subscription" + await adapter._handle_model_subscription_disconnect("anthropic") + assert clients[-1] is api_client + assert not tokens.has_credential("anthropic") + assert not state["loggedIn"] + + asyncio.run(run()) + assert len(launched) == 2 + assert all(process.poll() is not None for process in launched) diff --git a/tests/llm/golden/test_golden_payloads.py b/tests/llm/golden/test_golden_payloads.py index 0225e515..3391a0a2 100644 --- a/tests/llm/golden/test_golden_payloads.py +++ b/tests/llm/golden/test_golden_payloads.py @@ -236,24 +236,23 @@ def test_provider_request_quirks(golden): def _payload(provider, model): iface, rec = golden(provider, model) iface.generate_response(system_prompt="respond in json " * 40, user_prompt="hi") - return [c for c in rec.calls if c["method"] == "chat.completions.create"][0][ + payload = [c for c in rec.calls if c["method"] == "chat.completions.create"][0][ "payload" ] + assert iface._output_reservation(iface.reasoning_decision()) == payload.get( + "max_completion_tokens", payload.get("max_tokens") + ) + return payload # Perplexity: json_object is a hard 400 → must be omitted. ppx = _payload("perplexity", "sonar-pro") assert "response_format" not in ppx - # LM Studio: json_object unsupported → omitted. + # LM Studio: json_object unsupported → omitted. It also does not accept + # the prompt_cache_key routing hint used by some cloud providers. lms = _payload("lmstudio", "openai/gpt-oss-20b") assert "response_format" not in lms - - # OmniRoute (local OpenAI-compatible router): a routed backend may reject - # json_object → omitted; and as a proxy it must NOT receive prompt_cache_key - # (KV-safe — avoids a 400, gains nothing). - omni = _payload("omniroute", "auto") - assert "response_format" not in omni - assert "prompt_cache_key" not in (omni.get("extra_body") or {}) + assert "prompt_cache_key" not in (lms.get("extra_body") or {}) # Qwen: temperature 0 is rejected → sent as 0.01 (not 0.0, not omitted). qwen = _payload("qwen", "qwen-max") diff --git a/tests/test_context_budget.py b/tests/test_context_budget.py index 39c36990..25d119dd 100644 --- a/tests/test_context_budget.py +++ b/tests/test_context_budget.py @@ -307,6 +307,29 @@ def test_an_uncatalogued_model_folds_at_the_settings_window(): assert _folds_after(iface, 120_000) +@pytest.mark.parametrize( + "provider,model,output_cap", + [ + ("qwen", "qwen-max", 8192), + ("groq", "unruled-model", 32768), + ("nvidia", "meta/llama-3.3-70b-instruct", 16384), + ("cerebras", "unruled-model", 32000), + ], +) +def test_context_checks_reserve_the_providers_capped_output( + provider, model, output_cap +): + iface = _make(provider, model) + iface.max_tokens = 50000 + decision = iface.reasoning_decision() + window, max_input = iface._context_limits() + budget = min(window - output_cap, max_input or window) + + assert iface._output_reservation(decision) == output_cap + iface._check_context_fits("system", "hi", reasoning=decision) + assert _folds_after(iface, budget) + + def test_a_catalogued_model_folds_at_its_own_window(): """The settings window is ignored: 200,000 - output 8,000.""" iface = _make() diff --git a/tests/test_llm_reinitialize.py b/tests/test_llm_reinitialize.py index 0b820c6b..e8b01328 100644 --- a/tests/test_llm_reinitialize.py +++ b/tests/test_llm_reinitialize.py @@ -62,6 +62,28 @@ def test_reinitialize_noop_preserves_everything(llm_interface): assert llm_interface._session_system_prompts["task-1:reasoning"] == "system prompt" +def test_reinitialize_rebuilds_when_a_subscription_connects(llm_interface): + """Signing in to a subscription leaves the settings unchanged, but the + factory now builds a different client, so the reinitialize must run.""" + subscription_ctx = {**_make_ctx(), "auth_mode": "subscription"} + with ( + patch.object(ModelFactory, "create", return_value=subscription_ctx) as create, + patch("app.config.get_llm_model", return_value="claude-a"), + patch( + "agent_core.core.impl.llm.interface._subscription_connected", + return_value=not llm_interface._init_subscription, + ), + ): + ok = llm_interface.reinitialize( + provider="anthropic", api_key="key-a", base_url="" + ) + + assert ok is True + create.assert_called_once() + assert llm_interface._auth_mode == "subscription" + assert llm_interface._session_histories["task-1:reasoning"] + + def test_reinitialize_model_only_preserves_histories(llm_interface): """Same provider, different model: histories survive, model updates.""" with ( diff --git a/tests/test_settings_transactions.py b/tests/test_settings_transactions.py new file mode 100644 index 00000000..a2c8ac10 --- /dev/null +++ b/tests/test_settings_transactions.py @@ -0,0 +1,387 @@ +"""Concurrent settings changes compose, and readers only see complete JSON.""" + +import asyncio +import json +import threading +from types import SimpleNamespace +from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError + +import pytest + +from app import config, settings_store +from app.ui_layer.settings import ( + memory_settings, + model_settings, + proactive_settings, + provider_settings, +) +from craftos_integrations.config import ConfigStore +from craftos_integrations.credentials_store import save_credential +from craftos_integrations.llm_oauth import claude_code + + +@pytest.fixture +def settings_path(tmp_path, monkeypatch): + path = tmp_path / "settings.json" + path.write_text( + json.dumps({"model": {"llm_provider": "anthropic"}, "sentinel": "keep"}) + ) + for module in ( + config, + model_settings, + provider_settings, + memory_settings, + proactive_settings, + ): + monkeypatch.setattr(module, "SETTINGS_CONFIG_PATH", path) + monkeypatch.setattr(ConfigStore, "project_root", tmp_path) + monkeypatch.setattr(config, "_settings_cache", None) + return path + + +@pytest.mark.parametrize( + "other", ["model", "auth", "key", "memory", "proactive", "language"] +) +def test_overlapping_settings_mutations_preserve_both_changes( + settings_path, monkeypatch, other +): + first_read = threading.Event() + release_first = threading.Event() + second_started = threading.Event() + real_load = model_settings._load_settings + + def paused_load(): + snapshot = real_load() + if not first_read.is_set(): + first_read.set() + assert release_first.wait(5) + return snapshot + + monkeypatch.setattr(model_settings, "_load_settings", paused_load) + + def second_change(): + second_started.set() + if other == "model": + return model_settings.update_model_settings( + vlm_model="new-vlm", include_subscription_status=False + ) + if other == "auth": + return provider_settings._persist_auth_mode("anthropic", "subscription") + if other == "key": + return provider_settings.save_settings_to_json("anthropic", "fake-key") + if other == "memory": + return memory_settings.set_memory_processing_threshold(25) + if other == "proactive": + return proactive_settings.set_proactive_mode(False) + return config.set_ui_language("fr") + + with ThreadPoolExecutor(max_workers=2) as pool: + first = pool.submit( + model_settings.update_model_settings, + llm_model="new-llm", + include_subscription_status=False, + ) + assert first_read.wait(5) + second = pool.submit(second_change) + try: + assert second_started.wait(5) + # The second transaction cannot finish while the first holds its snapshot. + with pytest.raises(FutureTimeoutError): + second.result(timeout=0.1) + finally: + release_first.set() + assert first.result(timeout=5)["success"] + second.result(timeout=5) + + saved = json.loads(settings_path.read_text()) + assert saved["sentinel"] == "keep" + assert saved["model"]["llm_model"] == "new-llm" + expected = { + "model": ("model", "vlm_model", "new-vlm"), + "auth": ("auth_mode", "anthropic", "subscription"), + "key": ("api_keys", "anthropic", "fake-key"), + "memory": ("memory", "processing_threshold", 25), + "proactive": ("proactive", "enabled", False), + "language": ("general", "ui_language", "fr"), + } + section, key, value = expected[other] + assert saved[section][key] == value + + +def test_subscription_status_does_not_hold_the_settings_lock( + settings_path, monkeypatch +): + save_credential( + claude_code.CRED_FILE, + claude_code.ClaudeCodeConnection(profile_version=claude_code.PROFILE_VERSION), + ) + checking_status = threading.Event() + release_status = threading.Event() + + def slow_status(): + checking_status.set() + assert release_status.wait(5) + return {"connected": True} + + monkeypatch.setattr(claude_code, "auth_status", slow_status) + with ThreadPoolExecutor(max_workers=2) as pool: + saving = pool.submit(model_settings.update_model_settings, llm_model="new-llm") + assert checking_status.wait(5) + try: + # Auth-mode persistence must not wait for the CLI's ten-second timeout. + pool.submit( + provider_settings._persist_auth_mode, "anthropic", "subscription" + ).result(timeout=2) + finally: + release_status.set() + assert saving.result(timeout=5)["success"] + saved = json.loads(settings_path.read_text()) + assert saved["model"]["llm_model"] == "new-llm" + assert saved["auth_mode"]["anthropic"] == "subscription" + + +def test_failed_atomic_replace_preserves_the_previous_settings( + settings_path, monkeypatch +): + previous = settings_path.read_bytes() + + def fail(*args): + raise OSError("disk unavailable") + + monkeypatch.setattr(settings_store.os, "replace", fail) + assert not model_settings.update_model_settings( + llm_model="new-llm", include_subscription_status=False + )["success"] + assert settings_path.read_bytes() == previous + assert list(settings_path.parent.glob(".settings.json.*")) == [] + + +def test_concurrent_readers_never_observe_partial_json(settings_path): + stop = threading.Event() + observed = threading.Event() + + def read(): + while not stop.is_set(): + data = model_settings._load_settings() + assert data["sentinel"] == "keep" + observed.set() + + with ThreadPoolExecutor(max_workers=2) as pool: + reader = pool.submit(read) + try: + assert observed.wait(5) + for i in range(25): + assert model_settings.update_model_settings( + llm_model=f"model-{i}", include_subscription_status=False + )["success"] + finally: + stop.set() + reader.result(timeout=5) + + +@pytest.fixture +def adapter(settings_path, monkeypatch): + from app.ui_layer.adapters import browser_adapter + + monkeypatch.setattr( + browser_adapter, "validate_can_save", lambda **kwargs: {"can_save": True} + ) + adapter = object.__new__(browser_adapter.BrowserAdapter) + agent = SimpleNamespace(provider="anthropic", activations=[]) + + def reinitialize(provider): + agent.provider = provider + agent.activations.append(provider) + return True + + agent.reinitialize_llm = reinitialize + adapter._controller = SimpleNamespace(agent=agent) + adapter.sent = [] + + async def broadcast(message): + adapter.sent.append(message) + + adapter._broadcast = broadcast + return adapter + + +@pytest.mark.parametrize("second", ["save", "connect", "complete", "disconnect"]) +def test_slow_status_cannot_reorder_save_and_activation( + adapter, settings_path, monkeypatch, second +): + """Exercise actual handlers, settings transactions and cross-client ordering.""" + from app.ui_layer.adapters import browser_adapter + + checking = threading.Event() + release = threading.Event() + calls = 0 + + def status(): + nonlocal calls + calls += 1 + if calls == 1: + checking.set() + assert release.wait(5) + return {"connected": True} + + save_credential( + claude_code.CRED_FILE, + claude_code.ClaudeCodeConnection(profile_version=claude_code.PROFILE_VERSION), + ) + monkeypatch.setattr(claude_code, "auth_status", status) + + async def connect(provider): + return True, "Connected" + + monkeypatch.setattr(browser_adapter, "connect_subscription_async", connect) + monkeypatch.setattr( + browser_adapter, "complete_subscription", lambda *args: (True, "Connected") + ) + monkeypatch.setattr( + browser_adapter, "disconnect_subscription", lambda *args: (True, "Disconnected") + ) + + async def run(): + first = asyncio.create_task( + adapter._handle_model_settings_update({"llmProvider": "openai"}) + ) + try: + assert await asyncio.to_thread(checking.wait, 5) + # The first provider must already be live while its status is blocked. + assert adapter._controller.agent.provider == "openai" + if second == "save": + await asyncio.wait_for( + adapter._handle_model_settings_update({"llmProvider": "gemini"}), 2 + ) + elif second == "connect": + await asyncio.wait_for( + adapter._handle_model_subscription_connect("anthropic"), 2 + ) + elif second == "complete": + await asyncio.wait_for( + adapter._handle_model_subscription_complete( + "anthropic", "code", None + ), + 2, + ) + else: + await asyncio.wait_for( + adapter._handle_model_subscription_disconnect("openai"), 2 + ) + finally: + release.set() + await first + + asyncio.run(run()) + expected = { + "save": "gemini", + "connect": "anthropic", + "complete": "anthropic", + "disconnect": "openai", + }[second] + assert json.loads(settings_path.read_text())["model"]["llm_provider"] == expected + assert adapter._controller.agent.provider == expected + assert adapter._controller.agent.activations == ["openai", expected] + assert adapter.sent[-1]["data"]["llm_provider"] == expected + assert adapter.sent[-1]["data"]["subscription_oauth"]["anthropic"]["connected"] + + +@pytest.mark.parametrize("operation", ["connect", "complete"]) +def test_disconnect_prevents_late_subscription_activation( + adapter, settings_path, monkeypatch, operation +): + """Also cover the gap between credential completion and browser activation.""" + from app.ui_layer.adapters import browser_adapter + + ready = threading.Event() + release = threading.Event() + + async def connect(provider): + ready.set() + assert await asyncio.to_thread(release.wait, 5) + return True, "Connected" + + def complete(*args): + ready.set() + assert release.wait(5) + return True, "Connected" + + monkeypatch.setattr(browser_adapter, "connect_subscription_async", connect) + monkeypatch.setattr(browser_adapter, "complete_subscription", complete) + monkeypatch.setattr( + browser_adapter, "disconnect_subscription", lambda *args: (True, "Disconnected") + ) + monkeypatch.setattr( + browser_adapter, + "get_subscription_status", + lambda provider: {"connected": False}, + ) + + async def run(): + method = ( + adapter._handle_model_subscription_connect("anthropic") + if operation == "connect" + else adapter._handle_model_subscription_complete("anthropic", "code", None) + ) + pending = asyncio.create_task(method) + try: + assert await asyncio.to_thread(ready.wait, 5) + await adapter._handle_model_subscription_disconnect("anthropic") + finally: + release.set() + await pending + + asyncio.run(run()) + assert adapter._controller.agent.activations == ["anthropic"] # Disconnect only + assert adapter.sent[-1]["data"]["active_provider"] is None + assert json.loads(settings_path.read_text())["model"]["llm_provider"] == "anthropic" + + +@pytest.mark.parametrize("kind", ["image", "video"]) +def test_failed_media_activation_rolls_back_before_next_save( + adapter, settings_path, monkeypatch, kind +): + from app.ui_layer.adapters import browser_adapter + + entered = threading.Event() + release = threading.Event() + real_update = model_settings.update_model_settings + calls = 0 + + def update(**kwargs): + nonlocal calls + calls += 1 + result = real_update(**kwargs) + if calls == 1: + entered.set() + assert release.wait(5) + return result + + setattr( + adapter._controller.agent, f"reinitialize_{kind}_gen", lambda provider: False + ) + monkeypatch.setattr(browser_adapter, "update_model_settings", update) + provider_key = f"{kind}GenProvider" + + async def run(): + first = asyncio.create_task( + adapter._handle_model_settings_update( + {provider_key: "gemini" if kind == "image" else "openai"} + ) + ) + try: + assert await asyncio.to_thread(entered.wait, 5) + second = asyncio.create_task( + adapter._handle_model_settings_update({"llmProvider": "openai"}) + ) + await asyncio.sleep(0) + assert not second.done() + finally: + release.set() + await first + await second + + asyncio.run(run()) + saved = json.loads(settings_path.read_text())["model"] + assert saved[f"{kind}_gen_provider"] == ("openai" if kind == "image" else "gemini") + assert saved["llm_provider"] == adapter._controller.agent.provider == "openai"