import React, { useState, useEffect, useRef } from 'react'; import { api, NexusMarkdown, getStorageKey } from '@nexus/shared'; export const NexusMasterAgent: React.FC<{ workspaceId?: string }> = ({ workspaceId }) => { const [isOpen, setIsOpen] = useState(false); const [query, setQuery] = useState(""); const [messages, setMessages] = useState([]); const [loading, setLoading] = useState(false); const scrollRef = useRef(null); useEffect(() => { if (scrollRef.current) { scrollRef.current.scrollTop = scrollRef.current.scrollHeight; } }, [messages]); const handleQuery = async (e: React.FormEvent) => { e.preventDefault(); if (!query.trim()) return; const userMsg = { role: "user", content: query }; const assistantId = Date.now().toString(); // Use timestamp as temporary ID setMessages(prev => [...prev, userMsg, { id: assistantId, role: "assistant", content: "", isLoading: true }]); setQuery(""); setLoading(true); try { const token = localStorage.getItem(getStorageKey('token')); const response = await fetch(`${api.defaults.baseURL}nexus/stream/`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify({ query: userMsg.content, workspace_id: workspaceId, chat_history: messages.slice(-5).map(m => ({ role: m.role, content: m.content })) }) }); if (!response.ok) throw new Error('Stream request failed'); const reader = response.body?.getReader(); const decoder = new TextDecoder(); let accumulatedResponse = ""; if (reader) { setLoading(false); // Switch from total loading to token streaming while (true) { const { done, value } = await reader.read(); if (done) break; const chunk = decoder.decode(value, { stream: true }); const lines = chunk.split('\n'); for (const line of lines) { if (line.startsWith('data: ')) { try { const data = JSON.parse(line.slice(6)); if (data.type === 'token') { accumulatedResponse += data.content; setMessages(prev => prev.map(m => m.id === assistantId ? { ...m, content: accumulatedResponse, isLoading: false } : m )); } else if (data.type === 'status') { // Optional: Show status updates in the UI console.log("Nexus Status:", data.message); } else if (data.type === 'error') { throw new Error(data.message); } } catch (e) { // Ignore partial JSON or keep log } } } } } } catch (err: any) { console.error("Nexus Query Failed:", err); setMessages(prev => prev.map(m => m.id === assistantId ? { ...m, content: "I encountered an error connecting to the Nexus Master engine. Our internal neural network may be experiencing high telemetry load.", isLoading: false } : m )); } finally { setLoading(false); } }; return ( <> {/* Floating Pulse Hub (FAB) */}
setIsOpen(!isOpen)} style={{ position: 'fixed', bottom: 32, right: 32, width: 64, height: 64, border: 'none', borderRadius: '50%', background: 'var(--banner-gradient)', boxShadow: '0 10px 40px rgba(30, 64, 175, 0.4)', cursor: 'pointer', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275)', transform: isOpen ? 'rotate(135deg)' : 'none' }} > {isOpen ? '×' : 'N'} {/* Pulse Ring */} {!isOpen && (
)} {/* Live Indicator */}
{/* Glassmorphic Interaction Pane */} {isOpen && (
{/* Header */}
N
Nexus Master
Operational Intelligence
{/* Messages */}
{messages.length === 0 && (
🪐
Nexus Command
Strategic intelligence interface active. Query workspace telemetry, ticket states, or documentation.
)} {messages.map((m, i) => (
{m.isLoading && !m.content ? (
{[0,1,2].map(d => (
))}
) : ( )}
))}
{/* Footer Input */}
setQuery(e.target.value)} style={{ flex: 1, padding: '12px 16px', border: 'none', background: 'none', fontSize: 14, outline: 'none', fontWeight: 600, color: 'var(--text1)' }} />
)} ); };