"use client"; import { useState, useEffect, useRef } from "react"; import { Card, Button, ModelSelectModal, ManualConfigModal } from "@/shared/components"; import Image from "next/image"; import BaseUrlSelect from "./BaseUrlSelect"; import ApiKeySelect from "./ApiKeySelect"; import { matchKnownEndpoint } from "./cliEndpointMatch"; const ENDPOINT = "/api/cli-tools/deepseek-tui-settings"; export default function DeepSeekTuiToolCard({ tool, isExpanded, onToggle, baseUrl, hasActiveProviders, apiKeys, activeProviders, cloudEnabled, initialStatus, tunnelEnabled, tunnelPublicUrl, tailscaleEnabled, tailscaleUrl, }) { const [deepseekStatus, setDeepseekStatus] = useState(initialStatus || null); const [checking, setChecking] = useState(false); const [applying, setApplying] = useState(false); const [restoring, setRestoring] = useState(false); const [message, setMessage] = useState(null); const [selectedApiKey, setSelectedApiKey] = useState(""); const [selectedModel, setSelectedModel] = useState(""); const [modalOpen, setModalOpen] = useState(false); const [modelAliases, setModelAliases] = useState({}); const [showManualConfigModal, setShowManualConfigModal] = useState(false); const [customBaseUrl, setCustomBaseUrl] = useState(""); const hasInitializedModel = useRef(false); const getConfigStatus = () => { if (!deepseekStatus?.installed) return null; const openaiSection = deepseekStatus.settings?.["providers.openai"]; if (!openaiSection?.base_url) return "not_configured"; if (matchKnownEndpoint(openaiSection.base_url, { tunnelPublicUrl, tailscaleUrl })) return "configured"; return "other"; }; const configStatus = getConfigStatus(); useEffect(() => { if (apiKeys?.length > 0 && !selectedApiKey) { setSelectedApiKey(apiKeys[0].key); } }, [apiKeys, selectedApiKey]); useEffect(() => { if (initialStatus) setDeepseekStatus(initialStatus); }, [initialStatus]); useEffect(() => { if (isExpanded && !deepseekStatus) { checkStatus(); fetchModelAliases(); } if (isExpanded) fetchModelAliases(); }, [isExpanded]); 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 (deepseekStatus?.installed && !hasInitializedModel.current) { hasInitializedModel.current = true; const openaiSection = deepseekStatus.settings?.["providers.openai"]; if (openaiSection?.model) setSelectedModel(openaiSection.model); } }, [deepseekStatus]); const checkStatus = async () => { setChecking(true); try { const res = await fetch(ENDPOINT); const data = await res.json(); setDeepseekStatus(data); } catch (error) { setDeepseekStatus({ installed: false, error: error.message }); } finally { setChecking(false); } }; const normalizeLocalhost = (url) => url.replace("://localhost", "://127.0.0.1"); const getLocalBaseUrl = () => { if (typeof window !== "undefined") { return normalizeLocalhost(window.location.origin); } return "http://127.0.0.1:20128"; }; const getEffectiveBaseUrl = () => { const url = customBaseUrl || getLocalBaseUrl(); return url.endsWith("/v1") ? url : `${url}/v1`; }; const handleApply = async () => { setApplying(true); setMessage(null); try { const keyToUse = selectedApiKey?.trim() || (apiKeys?.length > 0 ? apiKeys[0].key : null) || (!cloudEnabled ? "sk_9router" : null); const res = await fetch(ENDPOINT, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ baseUrl: getEffectiveBaseUrl(), apiKey: keyToUse, model: selectedModel, }), }); const data = await res.json(); if (res.ok) { setMessage({ type: "success", text: "Settings applied successfully!" }); checkStatus(); } else { setMessage({ type: "error", text: data.error || "Failed to apply settings" }); } } catch (error) { setMessage({ type: "error", text: error.message }); } finally { setApplying(false); } }; const handleReset = async () => { setRestoring(true); setMessage(null); try { const res = await fetch(ENDPOINT, { method: "DELETE" }); const data = await res.json(); if (res.ok) { setMessage({ type: "success", text: "Settings reset successfully!" }); setSelectedModel(""); checkStatus(); } else { setMessage({ type: "error", text: data.error || "Failed to reset settings" }); } } catch (error) { setMessage({ type: "error", text: error.message }); } finally { setRestoring(false); } }; const handleModelSelect = (model) => { setSelectedModel(model.value); setModalOpen(false); }; const getManualConfigs = () => { const keyToUse = (selectedApiKey && selectedApiKey.trim()) ? selectedApiKey : (!cloudEnabled ? "sk_9router" : ""); const tomlContent = `[providers.openai] base_url = "${getEffectiveBaseUrl()}" api_key = "${keyToUse}" model = "${selectedModel || "provider/model-id"}" `; return [ { filename: "~/.deepseek/config.toml", content: tomlContent }, ]; }; 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 && (
{checking && (
progress_activity Checking DeepSeek TUI...
)} {!checking && deepseekStatus && !deepseekStatus.installed && (
warning

DeepSeek TUI not detected locally

Install via npm:

npm install -g deepseek-tui

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

)} {!checking && deepseekStatus?.installed && ( <>
{tool.notes && tool.notes.length > 0 && (
{tool.notes.map((note, idx) => (
{note.type === "warning" ? "warning" : note.type === "error" ? "error" : "info"} {note.text}
))}
)}
Select Endpoint arrow_forward
{deepseekStatus?.settings?.["providers.openai"]?.base_url && (
Current arrow_forward {deepseekStatus.settings["providers.openai"].base_url}
)}
API Key arrow_forward
Default Model arrow_forward
setSelectedModel(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" /> {selectedModel && }
{message && (
{message.type === "success" ? "check_circle" : "error"} {message.text}
)}
)}
)} setModalOpen(false)} onSelect={handleModelSelect} selectedModel={selectedModel} activeProviders={activeProviders} modelAliases={modelAliases} title="Select Model for DeepSeek TUI" /> setShowManualConfigModal(false)} title="DeepSeek TUI - Manual Configuration" configs={getManualConfigs()} />
); }