"use client"; import { useState, useEffect, useRef } from "react"; import { Card, Button, ModelSelectModal, ManualConfigModal, Tooltip } from "@/shared/components"; import Image from "next/image"; import BaseUrlSelect from "./BaseUrlSelect"; import ApiKeySelect from "./ApiKeySelect"; import { matchKnownEndpoint } from "./cliEndpointMatch"; const CLOUD_URL = process.env.NEXT_PUBLIC_CLOUD_URL; export default function ClaudeToolCard({ tool, isExpanded, onToggle, activeProviders, modelMappings, onModelMappingChange, baseUrl, hasActiveProviders, apiKeys, cloudEnabled, initialStatus, tunnelEnabled, tunnelPublicUrl, tailscaleEnabled, tailscaleUrl, }) { const [claudeStatus, setClaudeStatus] = useState(initialStatus || 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 [ccFilterNaming, setCcFilterNaming] = useState(false); const hasInitializedModels = useRef(false); const getConfigStatus = () => { if (!claudeStatus?.installed) return null; const currentUrl = claudeStatus.settings?.env?.ANTHROPIC_BASE_URL; if (!currentUrl) return "not_configured"; if (matchKnownEndpoint(currentUrl, { tunnelPublicUrl, tailscaleUrl, cloudUrl: cloudEnabled ? CLOUD_URL : null })) return "configured"; return "other"; }; const configStatus = getConfigStatus(); useEffect(() => { if (apiKeys?.length > 0 && !selectedApiKey) { setSelectedApiKey(apiKeys[0].key); } }, [apiKeys, selectedApiKey]); useEffect(() => { if (initialStatus) setClaudeStatus(initialStatus); }, [initialStatus]); useEffect(() => { if (isExpanded && !claudeStatus) { checkClaudeStatus(); fetchModelAliases(); } if (isExpanded) fetchModelAliases(); }, [isExpanded]); useEffect(() => { fetch("/api/settings").then(r => r.json()).then(data => { setCcFilterNaming(!!data.ccFilterNaming); }).catch(() => {}); }, []); const handleCcFilterNamingToggle = async (e) => { const value = e.target.checked; setCcFilterNaming(value); await fetch("/api/settings", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ccFilterNaming: value }), }).catch(() => {}); }; 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 = () => { const url = customBaseUrl || baseUrl; return url.endsWith("/v1") ? url : `${url}/v1`; }; const getDisplayUrl = () => { const url = customBaseUrl || baseUrl; return url.endsWith("/v1") ? url : `${url}/v1`; }; 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({ hasCompletedOnboarding: true, 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 detected locally

Manual configuration is still available if 9router is deployed on a remote server.

{showInstallGuide && (

Installation Guide

macOS / Linux / Windows:

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

After installation, run claude to verify.

)}
)} {!checkingClaude && claudeStatus?.installed && ( <>
{/* Endpoint (selector) */}
Select Endpoint arrow_forward
{/* Current configured */} {claudeStatus?.settings?.env?.ANTHROPIC_BASE_URL && (
Current arrow_forward {claudeStatus.settings.env.ANTHROPIC_BASE_URL}
)} {/* API Key */}
API Key arrow_forward
{/* Model Mappings */} {tool.defaultModels.map((model) => (
{model.name} arrow_forward
onModelMappingChange(model.alias, e.target.value)} placeholder="provider/model-id" className="w-full min-w-0 pl-2 pr-7 py-2 bg-surface rounded border border-border text-xs focus:outline-none focus:ring-1 focus:ring-primary/50 sm:py-1.5" /> {modelMappings[model.alias] && }
))} {/* CC Filter Naming */}
Filter naming arrow_forward
{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()} />
); }