import React, { useState, useEffect } from "react"; import { motion, AnimatePresence } from "motion/react"; import { ShieldAlert, Zap, Activity, Cpu, Terminal, MessageSquare, Users, Settings, ShieldCheck, Search, Lock, Radio, Layers, Bot, BrainCircuit, Webhook, Code, Plus, Trash2, Play, ExternalLink, Command, Server, LogOut, User, Moon, Sun, Bell, BellOff, PenTool, GitBranch, Link as LinkIcon, Telescope, Rocket } from "lucide-react"; import { v4 as uuidv4 } from "uuid"; import { GUNDAM_SERVICES, GUNDAM_MANIFEST } from "./gundam_core"; import { callMcpTool } from "./services/mcpService"; export default function App() { const [activeTab, setActiveTab] = useState("dashboard"); const [logs, setLogs] = useState<{id: number, msg: string, type: string, timestamp?: string}[]>([]); const [isScanning, setIsScanning] = useState(false); // Auth State const [user, setUser] = useState(null); const [userSettings, setUserSettings] = useState(null); const [isAuthLoading, setIsAuthLoading] = useState(true); const [authMode, setAuthMode] = useState<"login" | "register">("login"); const [authUsername, setAuthUsername] = useState(""); const [authPassword, setAuthPassword] = useState(""); const [authError, setAuthError] = useState(""); // Data States const [bots, setBots] = useState([]); const [models, setModels] = useState([]); const [webhooks, setWebhooks] = useState([]); const [mainframeModules, setMainframeModules] = useState([]); const [lilithData, setLilithData] = useState({ events: [], balances: [], agents: [], swarmPhase: 'L5' }); const [isDeployModalOpen, setIsDeployModalOpen] = useState(false); const [isModelModalOpen, setIsModelModalOpen] = useState(false); const [spaceData, setSpaceData] = useState(null); const [isSpaceLoading, setIsSpaceLoading] = useState(false); const [threatHistory, setThreatHistory] = useState([]); const [newBotName, setNewBotName] = useState(""); const [newBotToken, setNewBotToken] = useState(""); const [newModelName, setNewModelName] = useState(""); const [newModelPath, setNewModelPath] = useState(""); const [testingModelId, setTestingModelId] = useState(null); const [selectedAgentId, setSelectedAgentId] = useState(null); const [chimeraResults, setChimeraResults] = useState({ axioms: [], solutions: [] }); const [chaosTransformed, setChaosTransformed] = useState([]); // Discord Management State const [selectedDiscordBot, setSelectedDiscordBot] = useState(null); const [discordGuilds, setDiscordGuilds] = useState([]); const [selectedGuild, setSelectedGuild] = useState(null); const [discordChannels, setDiscordChannels] = useState([]); const [selectedChannel, setSelectedChannel] = useState(null); const [discordMessage, setDiscordMessage] = useState(""); // Multilingual Mesh State const [meshCores, setMeshCores] = useState([]); const [elixirSource, setElixirSource] = useState(""); const [compiledRust, setCompiledRust] = useState(""); const [isCompiling, setIsCompiling] = useState(false); // Shaping State const [shapingAffordances, setShapingAffordances] = useState<{ui: string[], code: string[]}>({ ui: ["View Threat Map", "Trigger Protocol 7", "Deploy Bot"], code: ["rust_analyze()", "elixir_swarm_init()", "ballerina_dispatch()"] }); const [shapingConnections, setShapingConnections] = useState<{from: string, to: string}[]>([]); const [rippleResults, setRippleResults] = useState(null); const [isRippleChecking, setIsRippleChecking] = useState(false); const [newAffordance, setNewAffordance] = useState(""); const [affordanceType, setAffordanceType] = useState<"ui" | "code">("ui"); // File Browser State const [isFileBrowserOpen, setIsFileBrowserOpen] = useState(false); const [currentPath, setCurrentPath] = useState(""); const [browserFiles, setBrowserFiles] = useState([]); const [isBrowserLoading, setIsBrowserLoading] = useState(false); // MCP State const [mcpTools, setMcpTools] = useState([]); const [mcpLogs, setMcpLogs] = useState([]); const [isMcpConnecting, setIsMcpConnecting] = useState(false); const [mcpEventSource, setMcpEventSource] = useState(null); // Mainframe State const [systemStats, setSystemStats] = useState(null); const [isMainframeInstalled, setIsMainframeInstalled] = useState(localStorage.getItem("mainframe_installed") === "true"); const [isInstallingMainframe, setIsInstallingMainframe] = useState(false); const [installProgress, setInstallProgress] = useState(0); useEffect(() => { checkAuth(); }, []); useEffect(() => { if (!user) return; fetchData(); fetchSystemStats(); fetchThreatHistory(); const interval = setInterval(() => { fetchLogs(); fetchSystemStats(); fetchData(); fetchThreatHistory(); if (isScanning) { // Keep the "meticulous scan" logs for flavor, but mix with real logs const newLog = { id: Date.now(), msg: `[${GUNDAM_SERVICES[Math.floor(Math.random() * GUNDAM_SERVICES.length)].language}] Meticulous scan: No domineering vectors detected.`, type: "info" }; setLogs(prev => [newLog, ...prev].slice(0, 50)); } }, 3000); return () => clearInterval(interval); }, [isScanning, user]); const checkAuth = async () => { try { const res = await fetch("/api/auth/me"); if (res.ok) { const data = await res.json(); setUser(data.user); setUserSettings(data.settings); } } catch (err) { console.error("Auth check failed:", err); } finally { setIsAuthLoading(false); } }; const handleLogin = async (e: React.FormEvent) => { e.preventDefault(); setAuthError(""); try { const res = await fetch("/api/auth/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username: authUsername, password: authPassword }) }); const data = await res.json(); if (res.ok) { checkAuth(); } else { setAuthError(data.error || "Login failed"); } } catch (err) { setAuthError("Network error"); } }; const handleRegister = async (e: React.FormEvent) => { e.preventDefault(); setAuthError(""); try { const res = await fetch("/api/auth/register", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username: authUsername, password: authPassword }) }); const data = await res.json(); if (res.ok) { setAuthMode("login"); setAuthError("Registration successful. Please login."); } else { setAuthError(data.error || "Registration failed"); } } catch (err) { setAuthError("Network error"); } }; const handleLogout = async () => { await fetch("/api/auth/logout", { method: "POST" }); setUser(null); setUserSettings(null); setActiveTab("dashboard"); }; const updateSettings = async (newSettings: any) => { try { const res = await fetch("/api/user/settings", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(newSettings) }); if (res.ok) { setUserSettings({ ...userSettings, ...newSettings }); } } catch (err) { console.error("Failed to update settings:", err); } }; useEffect(() => { if (selectedDiscordBot) { fetch(`/api/discord/guilds/${selectedDiscordBot}`) .then(res => res.json()) .then(data => { if (Array.isArray(data)) setDiscordGuilds(data); else setDiscordGuilds([]); }); } else { setDiscordGuilds([]); setSelectedGuild(null); } }, [selectedDiscordBot]); useEffect(() => { if (selectedDiscordBot && selectedGuild) { fetch(`/api/discord/channels/${selectedDiscordBot}/${selectedGuild}`) .then(res => res.json()) .then(data => { if (Array.isArray(data)) setDiscordChannels(data); else setDiscordChannels([]); }); } else { setDiscordChannels([]); setSelectedChannel(null); } }, [selectedDiscordBot, selectedGuild]); useEffect(() => { if (activeTab === "mesh") { callMcpTool('multilingual_core_status', {}).then(res => { if (res.cores) setMeshCores(res.cores); }); } }, [activeTab]); const fetchLogs = async () => { try { const res = await fetch("/api/logs"); const data = await res.json(); // Map server logs to the UI format const serverLogs = data.map((l: any) => ({ id: l.id, msg: `[Bot ${l.bot_id.slice(0,4)}] ${l.message}`, type: l.type, timestamp: l.timestamp })); setLogs(prev => { // Merge and deduplicate by ID if possible, or just replace // For simplicity, we'll just merge and sort const combined = [...serverLogs, ...prev.filter(p => !p.timestamp)]; // Keep scanning logs return combined.sort((a, b) => (b.id || b.timestamp) - (a.id || a.timestamp)).slice(0, 50); }); } catch (err) { console.error("Logs fetch error:", err); } }; const fetchThreatHistory = async () => { try { const res = await fetch("/api/threats/history"); const data = await res.json(); setThreatHistory(data); } catch (err) { console.error("Failed to fetch threat history:", err); } }; const fetchData = async () => { try { const [b, m, w, mod, lilith, agents] = await Promise.all([ fetch("/api/bots").then(r => r.json()), fetch("/api/models").then(r => r.json()), fetch("/api/webhooks").then(r => r.json()), fetch("/api/system/modules").then(r => r.json()), fetch("/api/lilith/nec").then(r => r.json()), fetch("/api/lilith/agents").then(r => r.json()) ]); setBots(b); setModels(m); setWebhooks(w); setMainframeModules(mod); setLilithData({ ...lilith, agents }); } catch (err) { console.error("Fetch error:", err); } }; const handleDeployBot = async () => { if (!newBotName || !newBotToken) return; await fetch("/api/bots", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: uuidv4(), name: newBotName, token: newBotToken, status: "deploying" }) }); setNewBotName(""); setNewBotToken(""); setIsDeployModalOpen(false); fetchData(); // Simulate deployment progress setTimeout(() => { setLogs(prev => [{ id: Date.now(), msg: `[System] Bot "${newBotName}" successfully deployed to edge node.`, type: "success" }, ...prev]); fetchData(); // Refresh to show "online" status if I had logic for it }, 3000); }; const toggleBotStatus = async (bot: any) => { const newStatus = bot.status === "online" ? "offline" : "online"; await fetch("/api/bots", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...bot, status: newStatus }) }); fetchData(); setLogs(prev => [{ id: Date.now(), msg: `[System] Bot "${bot.name}" status changed to ${newStatus}.`, type: "info" }, ...prev]); }; const deleteBot = async (id: string) => { if (!confirm("Are you sure you want to decommission this bot?")) return; await fetch(`/api/bots/${id}`, { method: "DELETE" }); fetchData(); setLogs(prev => [{ id: Date.now(), msg: `[System] Bot instance ${id.slice(0,8)} decommissioned.`, type: "warning" }, ...prev]); }; const handleAddModel = async () => { if (!newModelName || !newModelPath) return; const id = uuidv4(); const newModel = { id, name: newModelName, path: newModelPath, type: "GGUF" }; setLogs(prev => [{ id: Date.now(), msg: `[System] Attempting to mount GGUF vault: ${newModelName}...`, type: "info" }, ...prev]); try { const res = await fetch("/api/models", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(newModel) }); const data = await res.json(); if (data.success) { setLogs(prev => [{ id: Date.now(), msg: `[System] GGUF Model "${newModelName}" mounted successfully.`, type: "success" }, ...prev]); } else { setLogs(prev => [{ id: Date.now(), msg: `[Error] Failed to mount model: ${data.error}`, type: "error" }, ...prev]); } } catch (err) { setLogs(prev => [{ id: Date.now(), msg: `[Error] Network failure during model mount.`, type: "error" }, ...prev]); } setNewModelName(""); setNewModelPath(""); setIsModelModalOpen(false); fetchData(); }; const testModel = async (model: any) => { setTestingModelId(model.id); const startTime = Date.now(); setLogs(prev => [{ id: Date.now(), msg: `[Benchmark] Initiating latency test for ${model.name}...`, type: "info" }, ...prev]); try { const res = await fetch("/api/models/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: model.id, message: "Hello, confirm your status." }) }); const data = await res.json(); const endTime = Date.now(); const latency = endTime - startTime; if (data.response) { setLogs(prev => [{ id: Date.now(), msg: `[Benchmark] ${model.name} responded in ${latency}ms. Status: METICULOUS.`, type: "success" }, ...prev]); alert(`Model Response: ${data.response}\nLatency: ${latency}ms`); } else { setLogs(prev => [{ id: Date.now(), msg: `[Benchmark] ${model.name} failed to respond.`, type: "error" }, ...prev]); } } catch (err) { setLogs(prev => [{ id: Date.now(), msg: `[Benchmark] Error testing ${model.name}.`, type: "error" }, ...prev]); } finally { setTestingModelId(null); } }; const deleteModel = async (id: string) => { if (!confirm("Are you sure you want to unmount this model?")) return; await fetch(`/api/models/${id}`, { method: "DELETE" }); fetchData(); }; const fetchFiles = async (path?: string) => { setIsBrowserLoading(true); try { const url = path ? `/api/files/list?path=${encodeURIComponent(path)}` : "/api/files/list"; const res = await fetch(url); const data = await res.json(); if (res.ok) { setCurrentPath(data.currentPath); setBrowserFiles(data.files); } } catch (err) { console.error("Failed to fetch files:", err); } finally { setIsBrowserLoading(false); } }; const handleBrowseFiles = () => { setIsFileBrowserOpen(true); fetchFiles(); }; const navigateUp = () => { const parts = currentPath.split("/"); parts.pop(); const parentPath = parts.join("/") || "/"; fetchFiles(parentPath); }; const addWebhook = async () => { const name = prompt("Webhook Name:"); const url = prompt("Webhook URL:"); if (!name || !url) return; await fetch("/api/webhooks", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: uuidv4(), name, url }) }); fetchData(); }; const testWebhook = async (url: string) => { const msg = prompt("Test Message:", "G.U.N.D.A.M. system check operational."); if (!msg) return; const res = await fetch("/api/webhooks/test", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ url, message: msg }) }); const data = await res.json(); alert(data.success ? "Webhook fired successfully!" : "Webhook failed."); }; const connectMcp = () => { if (mcpEventSource) return; setIsMcpConnecting(true); const es = new EventSource("/api/mcp/sse"); es.onopen = () => { setIsMcpConnecting(false); setMcpLogs(prev => [...prev, { type: 'info', msg: 'MCP Connection established via SSE' }]); // Fetch tools once connected fetchMcpTools(); }; es.onerror = (e) => { console.error("MCP SSE Error:", e); setMcpLogs(prev => [...prev, { type: 'error', msg: 'MCP Connection failed' }]); setIsMcpConnecting(false); es.close(); setMcpEventSource(null); }; setMcpEventSource(es); }; const fetchMcpTools = async () => { try { // In a real MCP client, we'd send a JSON-RPC request over the transport. // For this demo, we'll simulate the tool discovery by hitting the same logic. const res = await fetch("/api/mcp/messages", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }) }); const data = await res.json(); if (data.result?.tools) { setMcpTools(data.result.tools); } } catch (err) { console.error("Failed to fetch MCP tools:", err); } }; const fetchSystemStats = async () => { try { const res = await fetch("/api/system/stats"); const data = await res.json(); setSystemStats(data); } catch (err) { console.error("Failed to fetch system stats:", err); } }; const runHygiene = async () => { setLogs(prev => [{ id: Date.now(), msg: "[Hygieia] Initiating Operative Deadman Sub-cycle (Absorbing B=6)...", type: "warning" }, ...prev]); try { const res = await fetch("/api/system/hygiene", { method: "POST" }); const data = await res.json(); if (data.success) { setLogs(prev => [{ id: Date.now(), msg: `[Hygieia] Sigma-Closure: ${data.sigma_closure.toFixed(8)} (${data.status}). Lattice Level: ${data.lattice_level}.`, type: "success" }, ...prev]); alert(`Hygiene Complete.\nSigma-Closure: ${data.sigma_closure.toFixed(8)}\nStatus: ${data.status}`); } } catch (err) { setLogs(prev => [{ id: Date.now(), msg: "[Hygieia] Hygiene sub-cycle failed to stabilize.", type: "error" }, ...prev]); } }; const installMainframe = () => { setIsInstallingMainframe(true); setInstallProgress(0); const interval = setInterval(() => { setInstallProgress(prev => { if (prev >= 100) { clearInterval(interval); setIsInstallingMainframe(false); setIsMainframeInstalled(true); localStorage.setItem("mainframe_installed", "true"); setLogs(prevLogs => [{ id: Date.now(), msg: "[System] Mainframe Core successfully installed and initialized.", type: "success" }, ...prevLogs]); return 100; } return prev + 2; }); }, 50); }; if (isAuthLoading) { return (

Initializing Core...

); } if (!user) { return (

G.U.N.D.A.M.

Project Meticulous Access

setAuthUsername(e.target.value)} className="w-full bg-white/5 border border-white/10 rounded-2xl px-5 py-4 text-sm focus:outline-none focus:border-indigo-500/50 transition-all pl-12" placeholder="meticulous_admin" required />
setAuthPassword(e.target.value)} className="w-full bg-white/5 border border-white/10 rounded-2xl px-5 py-4 text-sm focus:outline-none focus:border-indigo-500/50 transition-all pl-12" placeholder="••••••••" required />
{authError && (
{authError}
)}
); } return (
{/* Sidebar */}

G.U.N.D.A.M.

Project Meticulous

{user.username}

Operator

System Online
{/* Main Content */}

{activeTab.replace("-", " ")}

ToS Compliant Wrapper
{activeTab === "dashboard" && ( {/* Quick Actions */}
{/* Stats Grid */}
{[ { label: "Active Bots", value: bots.length.toString(), icon: Bot, color: "text-indigo-400" }, { label: "GGUF Models", value: models.length.toString(), icon: BrainCircuit, color: "text-emerald-400" }, { label: "Webhooks", value: webhooks.length.toString(), icon: Webhook, color: "text-amber-400" }, { label: "System Nodes", value: "4", icon: Cpu, color: "text-cyan-400" } ].map((stat, i) => (
0{i+1}

{stat.value}

{stat.label}

))}

Multi-Language Core Engine

{GUNDAM_SERVICES.map((service) => (

{service.name}

{service.language} • {service.role}

{service.status}
))}

System Logs

{logs.length > 0 ? logs.map(log => (
[{new Date(log.id).toLocaleTimeString()}] {log.msg}
)) : (
Initialize scan to begin monitoring...
)}
{/* Threat Analysis History */}

Recent Threat Analysis

{threatHistory.length > 0 ? threatHistory.map((threat, i) => (
{threat.target} {threat.threat_level}

{threat.findings}

{new Date(threat.timestamp).toLocaleString()} {threat.status}
)) : (

No threat analysis data available.

)}
)} {activeTab === "dev-panel" && (

Developer Control Plane

Meticulously manage G.U.N.D.A.M. infrastructure

setActiveTab("bots")}>

Bot Factory

Deploy and manage Discord bot instances

setActiveTab("models")}>

Model Vault

Manage GGUF local inference models

setActiveTab("webhooks")}>

Hook Router

Configure and test system webhooks

)} {activeTab === "bots" && (

Bot Deployment Factory

Meticulously deploy and manage your Discord bot fleet

{bots.map(bot => (

{bot.name}

{bot.status}

UUID: {bot.id}

))} {bots.length === 0 && (

No bots deployed in this sector.

)}
)} {activeTab === "models" && (

GGUF Model Vault

Meticulously manage and test local inference models

{models.map(model => (

{model.name}

{model.path}

{model.type}
))} {models.length === 0 && (

No models loaded in this sector.

)}
)} {activeTab === "mcp-console" && (

Model Context Protocol Console

Interact with G.U.N.D.A.M. tools via standardized MCP

Available Tools

{mcpTools.length > 0 ? mcpTools.map(tool => (

{tool.name}

{tool.description}

)) : (
Connect to MCP server to discover tools...
)}

MCP Traffic Log

{mcpLogs.map((log, i) => (
[{log.type}] {new Date().toLocaleTimeString()}

{log.msg}

{log.args &&
{JSON.stringify(log.args, null, 2)}
} {log.result &&
{JSON.stringify(log.result, null, 2)}
}
))} {mcpLogs.length === 0 && (
Waiting for MCP activity...
)}
)} {activeTab === "mesh" && (

Multilingual Mesh Core

Cross-language optimization engine (Rust, Julia, Elixir, Ballerina)

{meshCores.map(core => (
{core.name}
))}

Elixir Source

SOURCE_LIB_V1