"use client"; import { useState, useEffect, useRef } from "react"; import { Card, Button, ModelSelectModal, ManualConfigModal } from "@/shared/components"; import Image from "next/image"; const CLOUD_URL = process.env.NEXT_PUBLIC_CLOUD_URL; export default function ClaudeToolCard({ tool, isExpanded, onToggle, activeProviders, modelMappings, onModelMappingChange, baseUrl, hasActiveProviders, apiKeys, cloudEnabled, }) { const [claudeStatus, setClaudeStatus] = useState(null); const [checkingClaude, setCheckingClaude] = useState(false); const [applying, setApplying] = useState(false); const [restoring, setRestoring] = useState(false); const [message, setMessage] = useState(null); const [showInstallGuide, setShowInstallGuide] = useState(false); const [modalOpen, setModalOpen] = useState(false); const [currentEditingAlias, setCurrentEditingAlias] = useState(null); const [selectedApiKey, setSelectedApiKey] = useState(""); const [modelAliases, setModelAliases] = useState({}); const [showManualConfigModal, setShowManualConfigModal] = useState(false); const [customBaseUrl, setCustomBaseUrl] = useState(""); const hasInitializedModels = useRef(false); const getConfigStatus = () => { if (!claudeStatus?.installed) return null; const currentUrl = claudeStatus.settings?.env?.ANTHROPIC_BASE_URL; if (!currentUrl) return "not_configured"; const localMatch = currentUrl.includes("localhost") || currentUrl.includes("127.0.0.1"); const cloudMatch = cloudEnabled && CLOUD_URL && currentUrl.startsWith(CLOUD_URL); if (localMatch || cloudMatch) return "configured"; return "other"; }; const configStatus = getConfigStatus(); useEffect(() => { if (apiKeys?.length > 0 && !selectedApiKey) { setSelectedApiKey(apiKeys[0].key); } }, [apiKeys, selectedApiKey]); useEffect(() => { if (isExpanded && !claudeStatus) { checkClaudeStatus(); fetchModelAliases(); } }, [isExpanded, claudeStatus]); const fetchModelAliases = async () => { try { const res = await fetch("/api/models/alias"); const data = await res.json(); if (res.ok) setModelAliases(data.aliases || {}); } catch (error) { console.log("Error fetching model aliases:", error); } }; useEffect(() => { if (claudeStatus?.installed && !hasInitializedModels.current) { hasInitializedModels.current = true; const env = claudeStatus.settings?.env || {}; tool.defaultModels.forEach((model) => { if (model.envKey) { const value = env[model.envKey] || model.defaultValue || ""; // Only sync initial values from file once if (value) { onModelMappingChange(model.alias, value); } } }); // Only set selectedApiKey if it exists in apiKeys list const tokenFromFile = env.ANTHROPIC_AUTH_TOKEN; if (tokenFromFile && apiKeys?.some(k => k.key === tokenFromFile)) { setSelectedApiKey(tokenFromFile); } } }, [claudeStatus, apiKeys, tool.defaultModels, onModelMappingChange]); const checkClaudeStatus = async () => { setCheckingClaude(true); try { const res = await fetch("/api/cli-tools/claude-settings"); const data = await res.json(); setClaudeStatus(data); } catch (error) { setClaudeStatus({ installed: false, error: error.message }); } finally { setCheckingClaude(false); } }; const getEffectiveBaseUrl = () => customBaseUrl || baseUrl; const handleApplySettings = async () => { setApplying(true); setMessage(null); try { const env = { ANTHROPIC_BASE_URL: getEffectiveBaseUrl() }; // Get key from dropdown, fallback to first key or sk_9router for localhost const keyToUse = selectedApiKey?.trim() || (apiKeys?.length > 0 ? apiKeys[0].key : null) || (!cloudEnabled ? "sk_9router" : null); if (keyToUse) { env.ANTHROPIC_AUTH_TOKEN = keyToUse; } tool.defaultModels.forEach((model) => { const targetModel = modelMappings[model.alias]; if (targetModel && model.envKey) env[model.envKey] = targetModel; }); const res = await fetch("/api/cli-tools/claude-settings", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ env }), }); const data = await res.json(); if (res.ok) { setMessage({ type: "success", text: "Settings applied successfully!" }); setClaudeStatus(prev => ({ ...prev, hasBackup: true, settings: { ...prev?.settings, env } })); } else { setMessage({ type: "error", text: data.error || "Failed to apply settings" }); } } catch (error) { setMessage({ type: "error", text: error.message }); } finally { setApplying(false); } }; const handleResetSettings = async () => { setRestoring(true); setMessage(null); try { const res = await fetch("/api/cli-tools/claude-settings", { method: "DELETE" }); const data = await res.json(); if (res.ok) { setMessage({ type: "success", text: "Settings reset successfully!" }); tool.defaultModels.forEach((model) => onModelMappingChange(model.alias, model.defaultValue || "")); setSelectedApiKey(""); } else { setMessage({ type: "error", text: data.error || "Failed to reset settings" }); } } catch (error) { setMessage({ type: "error", text: error.message }); } finally { setRestoring(false); } }; const openModelSelector = (alias) => { setCurrentEditingAlias(alias); setModalOpen(true); }; const handleModelSelect = (model) => { if (currentEditingAlias) onModelMappingChange(currentEditingAlias, model.value); }; // Generate settings.json content for manual copy const getManualConfigs = () => { const keyToUse = (selectedApiKey && selectedApiKey.trim()) ? selectedApiKey : (!cloudEnabled ? "sk_9router" : ""); const env = { ANTHROPIC_BASE_URL: getEffectiveBaseUrl(), ANTHROPIC_AUTH_TOKEN: keyToUse }; tool.defaultModels.forEach((model) => { const targetModel = modelMappings[model.alias]; if (targetModel && model.envKey) env[model.envKey] = targetModel; }); return [ { filename: "~/.claude/settings.json", content: JSON.stringify({ env }, null, 2), }, ]; }; return (
{tool.name} { e.target.style.display = "none"; }} />

{tool.name}

{configStatus === "configured" && Connected} {configStatus === "not_configured" && Not configured} {configStatus === "other" && Other}

{tool.description}

expand_more
{isExpanded && (
{checkingClaude && (
progress_activity Checking Claude CLI...
)} {!checkingClaude && claudeStatus && !claudeStatus.installed && (
warning

Claude CLI not installed

Please install Claude CLI to use this feature.

{showInstallGuide && (

Installation Guide

macOS / Linux / Windows:

npm install -g @anthropic-ai/claude-code

After installation, run claude to verify.

)}
)} {!checkingClaude && claudeStatus?.installed && ( <>
{/* Base URL */}
Base URL arrow_forward setCustomBaseUrl(e.target.value)} placeholder="https://..." className="flex-1 px-2 py-1.5 bg-surface rounded border border-border text-xs focus:outline-none focus:ring-1 focus:ring-primary/50" /> {customBaseUrl && customBaseUrl !== baseUrl && ( )}
{/* API Key */}
API Key arrow_forward {apiKeys.length > 0 ? ( ) : ( {cloudEnabled ? "No API keys - Create one in Keys page" : "sk_9router (default)"} )}
{/* Model Mappings */} {tool.defaultModels.map((model) => (
{model.name} arrow_forward onModelMappingChange(model.alias, e.target.value)} placeholder="provider/model-id" className="flex-1 px-2 py-1.5 bg-surface rounded border border-border text-xs focus:outline-none focus:ring-1 focus:ring-primary/50" /> {modelMappings[model.alias] && }
))}
{message && (
{message.type === "success" ? "check_circle" : "error"} {message.text}
)}
)}
)} setModalOpen(false)} onSelect={handleModelSelect} selectedModel={currentEditingAlias ? modelMappings[currentEditingAlias] : null} activeProviders={activeProviders} modelAliases={modelAliases} title={`Select model for ${currentEditingAlias}`} /> setShowManualConfigModal(false)} title="Claude CLI - Manual Configuration" configs={getManualConfigs()} />
); }