Spaces:
Paused

nexus / frontend /apps /internal /src /components /NexusMasterAgent.tsx
dushyantsingh0
fix: allow staff cross-workspace live events via WebSockets
0f0e878
Raw History Blame Contribute Delete
11.3 kB
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<any[]>([]);
const [loading, setLoading] = useState(false);
const scrollRef = useRef<HTMLDivElement>(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 (
<>
<style>
{`
@keyframes nexus-pulse {
0% { transform: scale(1); opacity: 0.6; }
100% { transform: scale(1.6); opacity: 0; }
}
@keyframes nexus-slide-up {
from { opacity: 0; transform: translateY(40px) scale(0.95); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
@keyframes nexus-typing {
0%, 100% { transform: translateY(0); opacity: 0.3; }
50% { transform: translateY(-4px); opacity: 1; }
}
`}
</style>
{/* Floating Pulse Hub (FAB) */}
<div
onClick={() => 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'
}}
>
<span style={{ color: '#fff', fontSize: 24, fontWeight: 900, userSelect: 'none' }}>{isOpen ? '×' : 'N'}</span>
{/* Pulse Ring */}
{!isOpen && (
<div style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
borderRadius: '50%',
border: `2px solid var(--accent)`,
animation: 'nexus-pulse 2s infinite',
pointerEvents: 'none'
}} />
)}
{/* Live Indicator */}
<div style={{
position: 'absolute',
top: 0,
right: 0,
width: 16,
height: 16,
borderRadius: '50%',
background: 'var(--green)',
border: '3px solid var(--bg1)',
boxShadow: '0 0 12px var(--green)'
}} />
</div>
{/* Glassmorphic Interaction Pane */}
{isOpen && (
<div style={{
position: 'fixed',
bottom: 112,
right: 32,
width: 400,
height: 620,
maxHeight: 'calc(100vh - 160px)',
background: 'var(--bg-glass)',
backdropFilter: 'blur(30px) saturate(200%)',
borderRadius: 28,
border: '1px solid var(--border-hi)',
boxShadow: '0 30px 100px rgba(0,0,0,0.25)',
zIndex: 999,
display: 'flex',
flexDirection: 'column',
overflow: 'hidden',
animation: 'nexus-slide-up 0.6s cubic-bezier(0.19, 1, 0.22, 1)'
}}>
{/* Header */}
<div style={{ padding: '28px', background: 'rgba(255,255,255,0.05)', borderBottom: `1px solid var(--border)` }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
<div style={{
width: 40, height: 40, borderRadius: '12px',
background: 'var(--banner-gradient)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 16, color: '#fff', fontWeight: 900
}}>N</div>
<div>
<div style={{ fontSize: 18, fontWeight: 900, color: 'var(--text1)', letterSpacing: '-0.02em' }}>Nexus Master</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<div style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--green)', boxShadow: '0 0 8px var(--green)' }} />
<span style={{ fontSize: 11, color: 'var(--text3)', fontWeight: 800, textTransform: 'uppercase', letterSpacing: '0.05em' }}>Operational Intelligence</span>
</div>
</div>
</div>
</div>
{/* Messages */}
<div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '24px', display: 'flex', flexDirection: 'column', gap: 24 }}>
{messages.length === 0 && (
<div style={{ textAlign: 'center', padding: '60px 24px' }}>
<div style={{ fontSize: 48, marginBottom: 20 }}>🪐</div>
<div style={{ fontSize: 20, fontWeight: 900, color: 'var(--text1)', marginBottom: 8 }}>Nexus Command</div>
<div style={{ fontSize: 14, color: 'var(--text3)', lineHeight: 1.6, fontWeight: 500 }}>
Strategic intelligence interface active. Query workspace telemetry, ticket states, or documentation.
</div>
</div>
)}
{messages.map((m, i) => (
<div key={i} style={{
alignSelf: m.role === 'user' ? 'flex-end' : 'flex-start',
maxWidth: '85%',
padding: '14px 20px',
borderRadius: m.role === 'user' ? '24px 24px 4px 24px' : '24px 24px 24px 4px',
background: m.role === 'user' ? 'var(--accent)' : 'var(--bg2)',
color: m.role === 'user' ? '#fff' : 'var(--text1)',
fontSize: 14,
lineHeight: 1.6,
boxShadow: m.role === 'assistant' ? '0 10px 30px rgba(0,0,0,0.05)' : '0 10px 20px rgba(30, 64, 175, 0.15)',
border: m.role === 'assistant' ? `1px solid var(--border)` : 'none',
wordBreak: 'break-word',
fontWeight: 500
}}>
{m.isLoading && !m.content ? (
<div style={{ display: 'flex', gap: 6, padding: '4px 0' }}>
{[0,1,2].map(d => (
<div key={d} style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)', animation: 'nexus-typing 1.2s infinite', animationDelay: `${d * 0.2}s` }} />
))}
</div>
) : (
<NexusMarkdown content={m.content} isMe={m.role === 'user'} />
)}
</div>
))}
</div>
{/* Footer Input */}
<form onSubmit={handleQuery} style={{ padding: '24px', background: 'rgba(255,255,255,0.02)', borderTop: `1px solid var(--border)` }}>
<div style={{ display: 'flex', gap: 12, background: 'var(--bg1)', padding: '8px', borderRadius: 20, border: `1px solid var(--border-hi)`, boxShadow: '0 4px 20px rgba(0,0,0,0.1)' }}>
<input
placeholder="Ask your command center..."
value={query}
onChange={e => setQuery(e.target.value)}
style={{
flex: 1, padding: '12px 16px', border: 'none', background: 'none',
fontSize: 14, outline: 'none', fontWeight: 600, color: 'var(--text1)'
}}
/>
<button
type="submit"
disabled={!query.trim() || loading}
style={{
width: 44, height: 44, borderRadius: '14px', border: 'none',
background: 'var(--banner-gradient)', color: '#fff', cursor: 'pointer',
display: 'flex', alignItems: 'center', justifyContent: 'center',
opacity: (!query.trim() || loading) ? 0.4 : 1,
transition: 'all 0.2s cubic-bezier(0.4, 0, 0.2, 1)'
}}
onMouseEnter={e => !(!query.trim() || loading) && (e.currentTarget.style.transform = 'scale(1.08) translateY(-2px)')}
onMouseLeave={e => e.currentTarget.style.transform = 'scale(1) translateY(0)'}
>
<div style={{ transform: 'rotate(-45deg) translate(2px, -2px)', fontSize: 18 }}>🚀</div>
</button>
</div>
</form>
</div>
)}
</>
);
};