"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 DroidToolCard({ tool, isExpanded, onToggle, baseUrl, hasActiveProviders, apiKeys, activeProviders, cloudEnabled, initialStatus, }) { const [droidStatus, setDroidStatus] = useState(initialStatus || null); const [checkingDroid, setCheckingDroid] = 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 (!droidStatus?.installed) return null; const currentConfig = droidStatus.settings?.customModels?.find(m => m.id === "custom:9Router-0"); if (!currentConfig) return "not_configured"; const localMatch = currentConfig.baseUrl?.includes("localhost") || currentConfig.baseUrl?.includes("127.0.0.1"); const cloudMatch = cloudEnabled && CLOUD_URL && currentConfig.baseUrl?.startsWith(CLOUD_URL); const tunnelMatch = baseUrl && currentConfig.baseUrl?.startsWith(baseUrl); if (localMatch || cloudMatch || tunnelMatch) return "configured"; return "other"; }; const configStatus = getConfigStatus(); useEffect(() => { if (apiKeys?.length > 0 && !selectedApiKey) { setSelectedApiKey(apiKeys[0].key); } }, [apiKeys, selectedApiKey]); useEffect(() => { if (initialStatus) setDroidStatus(initialStatus); }, [initialStatus]); useEffect(() => { if (isExpanded && !droidStatus) { checkDroidStatus(); 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 (droidStatus?.installed && !hasInitializedModel.current) { hasInitializedModel.current = true; const customModel = droidStatus.settings?.customModels?.find(m => m.id === "custom:9Router-0"); if (customModel) { if (customModel.model) setSelectedModel(customModel.model); if (customModel.apiKey && apiKeys?.some(k => k.key === customModel.apiKey)) { setSelectedApiKey(customModel.apiKey); } } } }, [droidStatus, apiKeys]); const checkDroidStatus = async () => { setCheckingDroid(true); try { const res = await fetch("/api/cli-tools/droid-settings"); const data = await res.json(); setDroidStatus(data); } catch (error) { setDroidStatus({ installed: false, error: error.message }); } finally { setCheckingDroid(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 keyToUse = selectedApiKey?.trim() || (apiKeys?.length > 0 ? apiKeys[0].key : null) || (!cloudEnabled ? "sk_9router" : null); const res = await fetch("/api/cli-tools/droid-settings", { 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!" }); checkDroidStatus(); } 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/droid-settings", { method: "DELETE" }); const data = await res.json(); if (res.ok) { setMessage({ type: "success", text: "Settings reset successfully!" }); setSelectedModel(""); setSelectedApiKey(""); checkDroidStatus(); } 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 settingsContent = { customModels: [ { model: selectedModel || "provider/model-id", id: "custom:9Router-0", index: 0, baseUrl: getEffectiveBaseUrl(), apiKey: keyToUse, displayName: selectedModel || "provider/model-id", maxOutputTokens: 131072, noImageSupport: false, provider: "openai", }, ], }; const platform = typeof navigator !== "undefined" && navigator.platform; const isWindows = platform?.toLowerCase().includes("win"); const settingsPath = isWindows ? "%USERPROFILE%\\.factory\\settings.json" : "~/.factory/settings.json"; return [ { filename: settingsPath, content: JSON.stringify(settingsContent, 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 && (
{checkingDroid && (
progress_activity Checking Factory Droid CLI...
)} {!checkingDroid && droidStatus && !droidStatus.installed && (
warning

Factory Droid CLI not installed

Please install Factory Droid CLI to use this feature.

)} {!checkingDroid && droidStatus?.installed && ( <>
{/* Current Base URL */} {droidStatus?.settings?.customModels?.find(m => m.id === "custom:9Router-0")?.baseUrl && (
Current arrow_forward {droidStatus.settings.customModels.find(m => m.id === "custom:9Router-0").baseUrl}
)} {/* Base URL */}
Base URL arrow_forward setCustomBaseUrl(e.target.value)} placeholder="https://.../v1" 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 */}
Model arrow_forward setSelectedModel(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" /> {selectedModel && }
{message && (
{message.type === "success" ? "check_circle" : "error"} {message.text}
)}
)}
)} setModalOpen(false)} onSelect={handleModelSelect} selectedModel={selectedModel} activeProviders={activeProviders} modelAliases={modelAliases} title="Select Model for Factory Droid" /> setShowManualConfigModal(false)} title="Factory Droid - Manual Configuration" configs={getManualConfigs()} />
); }