From 921cd4ff3f791e407117ff15c0beeab20493fb43 Mon Sep 17 00:00:00 2001 From: ahmad-ajmal Date: Tue, 20 Oct 2026 14:11:27 +0100 Subject: [PATCH 1/7] Add Claude subscription access with an isolated Claude Code profile --- agent_core/core/models/claude_code_client.py | 157 +++++++ agent_core/core/models/connection_tester.py | 15 + agent_core/core/models/factory.py | 16 + agent_core/core/models/provider_config.py | 2 + app/ui_layer/adapters/browser_adapter.py | 4 +- .../frontend/src/locales/en/onboarding.json | 2 + .../frontend/src/locales/en/settings.json | 3 + .../Onboarding/OnboardingPage.module.css | 7 + .../src/pages/Onboarding/OnboardingPage.tsx | 22 +- .../src/pages/Settings/ModelSettings.tsx | 30 +- app/ui_layer/settings/provider_settings.py | 14 +- craftos_integrations/llm_oauth/README.md | 34 +- craftos_integrations/llm_oauth/__init__.py | 5 +- craftos_integrations/llm_oauth/claude_code.py | 231 ++++++++++ craftos_integrations/llm_oauth/tokens.py | 24 +- docs/CLAUDE_CODE_VALIDATION.md | 130 ++++++ .../claude-code/01-onboarding-sign-in.jpg | Bin 0 -> 26450 bytes .../claude-code/02-onboarding-connected.jpg | Bin 0 -> 23969 bytes .../claude-code/04-settings-connected.jpg | Bin 0 -> 55437 bytes .../claude-code/05-live-inference-error.jpg | Bin 0 -> 42765 bytes .../06-saved-model-after-reload.jpg | Bin 0 -> 55922 bytes .../claude-code/07-settings-disconnected.jpg | Bin 0 -> 56071 bytes .../claude-code/08-independent-profile.jpg | Bin 0 -> 50272 bytes .../09-private-profile-before-connect.jpg | Bin 0 -> 50272 bytes .../10-private-profile-login-pending.jpg | Bin 0 -> 47944 bytes .../test_claude_code_subscription.py | 423 ++++++++++++++++++ 26 files changed, 1087 insertions(+), 32 deletions(-) create mode 100644 agent_core/core/models/claude_code_client.py create mode 100644 craftos_integrations/llm_oauth/claude_code.py create mode 100644 docs/CLAUDE_CODE_VALIDATION.md create mode 100644 docs/validation/claude-code/01-onboarding-sign-in.jpg create mode 100644 docs/validation/claude-code/02-onboarding-connected.jpg create mode 100644 docs/validation/claude-code/04-settings-connected.jpg create mode 100644 docs/validation/claude-code/05-live-inference-error.jpg create mode 100644 docs/validation/claude-code/06-saved-model-after-reload.jpg create mode 100644 docs/validation/claude-code/07-settings-disconnected.jpg create mode 100644 docs/validation/claude-code/08-independent-profile.jpg create mode 100644 docs/validation/claude-code/09-private-profile-before-connect.jpg create mode 100644 docs/validation/claude-code/10-private-profile-login-pending.jpg create mode 100644 tests/integrations/test_claude_code_subscription.py 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..505be1d2 --- /dev/null +++ b/agent_core/core/models/claude_code_client.py @@ -0,0 +1,157 @@ +"""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 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)} + if 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..16cdecbc 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="Connect Claude subscription (Claude Code)", connection_test_model="claude-haiku-4-5-20251001", connection_test_max_tokens=1, default_models={ diff --git a/app/ui_layer/adapters/browser_adapter.py b/app/ui_layer/adapters/browser_adapter.py index ab357d7f..a416eefc 100644 --- a/app/ui_layer/adapters/browser_adapter.py +++ b/app/ui_layer/adapters/browser_adapter.py @@ -6636,7 +6636,9 @@ async def _handle_model_subscription_disconnect(self, provider: str) -> None: now that the subscription credential is gone. """ try: - success, message = disconnect_subscription(provider) + success, message = await asyncio.to_thread( + disconnect_subscription, provider + ) warning = None if success: try: 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..32810a0d 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,8 @@ "useOpenRouter": "Having connection issues? Use OpenRouter instead →" }, "sub": { + "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..ba49a46c 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,9 @@ "startingShort": "Starting..." }, "subscription": { + "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..df5418e0 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,10 @@ export function OnboardingPage() { )} + {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..40ac42f8 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}

+ )} ) 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/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 85890d24..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 @@ -358,144 +358,145 @@ def update_model_settings( 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( @@ -805,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 6f9ee964..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: @@ -236,6 +240,7 @@ def get_api_key_for_provider(provider: str) -> str: # ───────────────────────────────────────────────────────────────────── +@settings_transaction def _persist_auth_mode(provider: str, mode: str) -> None: """Write the UI-hint ``auth_mode`` for ``provider`` to settings.json. diff --git a/craftos_integrations/llm_oauth/claude_code.py b/craftos_integrations/llm_oauth/claude_code.py index ad6033a2..766d3ac8 100644 --- a/craftos_integrations/llm_oauth/claude_code.py +++ b/craftos_integrations/llm_oauth/claude_code.py @@ -172,7 +172,9 @@ def has_credential() -> bool: def status() -> Dict[str, Any]: if not has_credential(): return {"supported": True, "connected": False} - return {"supported": True, **auth_status()} + # 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]: diff --git a/docs/CLAUDE_CODE_VALIDATION.md b/docs/CLAUDE_CODE_VALIDATION.md index 1034f27b..c859a07b 100644 --- a/docs/CLAUDE_CODE_VALIDATION.md +++ b/docs/CLAUDE_CODE_VALIDATION.md @@ -11,6 +11,16 @@ 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 @@ -18,13 +28,19 @@ 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 tests: **56 passed**, including 19 new - regression cases for reasoning choices and event-loop isolation. +- 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, context-budget and Supabase conformance tests: **1000 passed**. + reliability, session-resume, context-readout, context-budget, settings-transaction + and Supabase conformance tests: **1047 passed**. `test_provider_request_quirks` now passes. -- Additional session-resume and context-readout regressions: **36 passed** - (**1036 passed** across the validation runs). +- 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 diff --git a/tests/integrations/test_claude_code_subscription.py b/tests/integrations/test_claude_code_subscription.py index 9aa2c3fe..a551e9bd 100644 --- a/tests/integrations/test_claude_code_subscription.py +++ b/tests/integrations/test_claude_code_subscription.py @@ -494,9 +494,81 @@ def test_status_detects_cli_logout_without_exporting_tokens(monkeypatch): 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 diff --git a/tests/test_settings_transactions.py b/tests/test_settings_transactions.py new file mode 100644 index 00000000..220258b3 --- /dev/null +++ b/tests/test_settings_transactions.py @@ -0,0 +1,177 @@ +"""Concurrent settings changes compose, and readers only see complete JSON.""" + +import json +import threading +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) From 92b5a1a41afaf63e09287ac36023df34c273f772 Mon Sep 17 00:00:00 2001 From: ahmad-ajmal Date: Wed, 21 Oct 2026 11:09:07 +0100 Subject: [PATCH 6/7] fix: order model activation and cancel stale Claude sign-ins Signed-off-by: ahmad-ajmal --- app/ui_layer/adapters/browser_adapter.py | 342 ++++++++++-------- craftos_integrations/llm_oauth/claude_code.py | 89 +++-- docs/CLAUDE_CODE_VALIDATION.md | 36 +- .../test_claude_code_subscription.py | 175 ++++++++- tests/test_settings_transactions.py | 210 +++++++++++ 5 files changed, 682 insertions(+), 170 deletions(-) diff --git a/app/ui_layer/adapters/browser_adapter.py b/app/ui_layer/adapters/browser_adapter.py index cbda2b86..230d0756 100644 --- a/app/ui_layer/adapters/browser_adapter.py +++ b/app/ui_layer/adapters/browser_adapter.py @@ -6126,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. @@ -6217,130 +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_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_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_video_gen_provider = _get_vg_provider() - prev_video_gen_model = _get_vg_model() + 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 = await asyncio.to_thread( - 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"), - ) + # 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"), + ) - # 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, - 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. + 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 - # 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, - 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: + 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 - await self._broadcast( - { - "type": "model_settings_update", - "data": result, - } - ) + # 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 + ) + 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( { @@ -6573,10 +6611,11 @@ 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 = await self._activate_provider_via_settings( - success, provider + 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) @@ -6606,7 +6645,7 @@ async def _handle_model_subscription_connect(self, provider: str) -> None: ) async def _activate_provider_via_settings( - self, connect_success: bool, provider: str + self, connect_success: bool, provider: str, *, request: object = None ) -> Optional[str]: """Reuse the manual-Save path to make ``provider`` the active LLM. @@ -6621,10 +6660,22 @@ async def _activate_provider_via_settings( if not connect_success: return None try: - await asyncio.to_thread(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 " @@ -6642,32 +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 = await asyncio.to_thread( - 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", @@ -6761,12 +6814,13 @@ 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 = await self._activate_provider_via_settings( - success, provider + success, provider, request=request ) await self._broadcast( { diff --git a/craftos_integrations/llm_oauth/claude_code.py b/craftos_integrations/llm_oauth/claude_code.py index 766d3ac8..9e777a89 100644 --- a/craftos_integrations/llm_oauth/claude_code.py +++ b/craftos_integrations/llm_oauth/claude_code.py @@ -190,6 +190,29 @@ def _save_connection(current: Dict[str, Any]) -> Tuple[bool, str]: _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: @@ -200,29 +223,33 @@ def _last_message(output: List[str]) -> str: return "" -def _browser_login() -> Tuple[bool, str]: +def _browser_login(attempt: int) -> Tuple[bool, str]: """Run ``claude auth login`` until the user approves in its browser tab.""" global _login_process try: - process = subprocess.Popen( - [*cli_command(), "auth", "login", "--claudeai"], - 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, - ) + 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}" - # A newer Connect replaces an abandoned sign-in instead of waiting for it. - with _login_lock: - previous, _login_process = _login_process, process - if previous is not None and previous.poll() is None: - previous.kill() output: List[str] = [] def read_output() -> None: @@ -235,11 +262,12 @@ def read_output() -> None: 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 = _login_process is not process - if not replaced: + replaced = attempt != _login_generation + if not replaced and process.poll() is not None: _login_process = None reader.join(timeout=5) if replaced: @@ -247,15 +275,23 @@ def read_output() -> None: if process.returncode: detail = _last_message(output) or "Claude Code could not sign in" return False, f"Claude sign-in failed: {detail}" - return _save_connection(auth_status()) + 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 _save_connection(current) - return _browser_login() + return _finish_login(attempt, current) + return _browser_login(attempt) async def run_login() -> Tuple[bool, str]: @@ -266,6 +302,17 @@ async def run_login() -> Tuple[bool, str]: 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: diff --git a/docs/CLAUDE_CODE_VALIDATION.md b/docs/CLAUDE_CODE_VALIDATION.md index c859a07b..44ca91cc 100644 --- a/docs/CLAUDE_CODE_VALIDATION.md +++ b/docs/CLAUDE_CODE_VALIDATION.md @@ -1,6 +1,38 @@ # Claude subscription validation report -## Review fixes: 21 October 2026 +## 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. Real-account acceptance remains the final merge gate, tracked below. + +## 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 @@ -95,7 +127,7 @@ The user was asked to complete Anthropic's sign-in in the browser opened by Clau ### Current manual acceptance 1. Open [CraftBot](http://localhost:27955/settings) and select Model. The previous shared account must no longer appear connected. -2. Click Connect and complete Anthropic's own browser sign-in for the CraftBot profile. +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. diff --git a/tests/integrations/test_claude_code_subscription.py b/tests/integrations/test_claude_code_subscription.py index a551e9bd..ba186af1 100644 --- a/tests/integrations/test_claude_code_subscription.py +++ b/tests/integrations/test_claude_code_subscription.py @@ -23,6 +23,7 @@ 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") @@ -193,7 +194,7 @@ def test_connect_waits_for_approval_in_the_cli_tab(monkeypatch, opened): ok, message = asyncio.run(tokens.connect("anthropic")) assert ok and "user@example.com" in message login = launched[0] - assert login.args == ["claude", "auth", "login", "--claudeai"] + 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 == [] @@ -272,7 +273,7 @@ async def broadcast(message): adapter._broadcast = broadcast - async def activate(ok, provider): + async def activate(ok, provider, **kwargs): return provider if ok else None adapter._activate_provider_via_settings = activate @@ -813,7 +814,7 @@ async def run(): asyncio.run(run()) assert sent[-1]["data"]["success"] if operation in ("image_rollback", "video_rollback"): - assert len(status_threads) == 2 + assert len(status_threads) == 1 assert sent[-1]["data"]["warning"] elif operation in ("connect", "complete"): assert sent[-1]["data"]["active_provider"] == "anthropic" @@ -854,3 +855,171 @@ def test_onboarding_settings_updates_can_skip_unused_live_status(monkeypatch): ) 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/test_settings_transactions.py b/tests/test_settings_transactions.py index 220258b3..a2c8ac10 100644 --- a/tests/test_settings_transactions.py +++ b/tests/test_settings_transactions.py @@ -1,7 +1,9 @@ """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 @@ -175,3 +177,211 @@ def read(): 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" From 2ba999696b7577c6c2e8c121269704eadc98667e Mon Sep 17 00:00:00 2001 From: ahmad-ajmal Date: Wed, 21 Oct 2026 11:11:41 +0100 Subject: [PATCH 7/7] docs: record final closure checks and account validation gap Signed-off-by: ahmad-ajmal --- docs/CLAUDE_CODE_VALIDATION.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/CLAUDE_CODE_VALIDATION.md b/docs/CLAUDE_CODE_VALIDATION.md index 44ca91cc..c3851ed3 100644 --- a/docs/CLAUDE_CODE_VALIDATION.md +++ b/docs/CLAUDE_CODE_VALIDATION.md @@ -30,7 +30,14 @@ 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. Real-account acceptance remains the final merge gate, tracked below. + 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