-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApp.tsx
More file actions
431 lines (375 loc) · 17.3 KB
/
Copy pathApp.tsx
File metadata and controls
431 lines (375 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
import React, { useState, useEffect, Suspense } from 'react';
import Sidebar from './components/Sidebar';
import { Agent, SystemMode, AutonomousConfig, WorkflowStage, IntrospectionLayer, UserRole, Project, MorphPayload, SystemMetrics, SystemProtocol } from './types';
import { DEFAULT_AUTONOMOUS_CONFIG, DEFAULT_API_CONFIG } from './constants';
import { api } from './utils/api';
import { systemBus } from './services/systemBus';
import LoginGate from './components/LoginGate';
import OnboardingTour from './components/OnboardingTour';
// CRITICAL COMPONENTS - Eager load for fast initial render
// [OPTIMIZATION] Dashboard is now Lazy Loaded to defer Recharts/Charts bundle
// import Dashboard from './components/Dashboard';
import ProtocolOverlay from './components/ProtocolOverlay';
import NotificationCenter from './components/NotificationCenter';
// LAZY LOAD SECONDARY COMPONENTS - Only loaded when tab is visited
const Dashboard = React.lazy(() => import('./components/Dashboard'));
const AgentOrchestrator = React.lazy(() => import('./components/AgentOrchestrator'));
const TerminalLog = React.lazy(() => import('./components/TerminalLog'));
const SystemControl = React.lazy(() => import('./components/SystemControl'));
const ContinuumMemoryExplorer = React.lazy(() => import('./components/ContinuumMemoryExplorer'));
const Settings = React.lazy(() => import('./components/Settings'));
const DynamicWorkspace = React.lazy(() => import('./components/DynamicWorkspace'));
const MediaStudio = React.lazy(() => import('./components/MediaStudio'));
const IntrospectionHub = React.lazy(() => import('./components/IntrospectionHub'));
const ChatWidget = React.lazy(() => import('./components/ChatWidget'));
const DrivePanel = React.lazy(() => import('./components/DrivePanel'));
const EmailPanel = React.lazy(() => import('./components/EmailPanel'));
const NexusCanvas = React.lazy(() => import('./components/canvas/NexusCanvas'));
// [OPTIMIZATION] Lazy load Visual Cortex to defer html2canvas/webgl utils
const VisualCortex = React.lazy(() => import('./components/VisualCortex').then(module => ({ default: module.VisualCortex })));
// NOTE: Backend services are no longer imported directly to avoid Vite build errors.
// The frontend now acts as a pure View layer, fetching state from the API.
declare global {
interface Window {
performance: any;
}
}
const App: React.FC = () => {
// ... (state definitions unchanged) ...
const [currentUserRole, setCurrentUserRole] = useState<UserRole>(UserRole.ADMIN);
const [activeTab, setActiveTab] = useState('dashboard');
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
const [agents, setAgents] = useState<Agent[]>([]);
const [autonomyConfig, setAutonomyConfig] = useState<AutonomousConfig>(DEFAULT_AUTONOMOUS_CONFIG);
const [liveThoughts, setLiveThoughts] = useState<string[]>([]);
// [NEW] Distributed Squad Thoughts (The "100% Real" Stuff)
const [squadThoughts, setSquadThoughts] = useState<Record<string, string[]>>({});
// Settings are now fetched or managed locally for UI preferences
const [appSettings, setAppSettings] = useState({
theme: { mode: 'dark', density: 'comfortable', accentColor: 'cyan', reduceMotion: false },
integrations: {},
registeredIntegrations: [],
permissions: {},
notifications: {},
language: 'en'
});
const [uiOverride, setUiOverride] = useState<MorphPayload | null>(null);
const [dashboardProjects, setDashboardProjects] = useState<Project[]>([]);
const [pendingProjectId, setPendingProjectId] = useState<string | null>(null);
const [metrics, setMetrics] = useState<SystemMetrics>({
activeAgents: 0,
agentsInVram: 0,
agentsInRam: 0,
introspectionDepth: (() => { try { return parseInt(localStorage.getItem('silhouette_introspection_depth') || '32'); } catch { return 32; } })(),
awarenessScore: 85.0,
fps: 60,
currentMode: (() => { try { return (localStorage.getItem('silhouette_power_mode') as SystemMode) || SystemMode.ECO; } catch { return SystemMode.ECO; } })(),
tokenUsageToday: 0,
currentStage: WorkflowStage.IDLE,
jsHeapSize: 0,
vramUsage: 0,
cpuTickDuration: 0,
netLatency: 0,
systemAlert: null
});
const [logs, setLogs] = useState<string[]>([]);
const [driveOpen, setDriveOpen] = useState(false);
const [emailOpen, setEmailOpen] = useState(false);
// ... (effects unchanged) ...
// Restore active tab
useEffect(() => {
const savedTab = localStorage.getItem('silhouette_active_tab');
if (savedTab) setActiveTab(savedTab);
}, []);
useEffect(() => {
localStorage.setItem('silhouette_active_tab', activeTab);
}, [activeTab]);
// ADAPTIVE POLLING with UNIFIED ENDPOINT
// - Uses single /full-state call instead of 4 separate calls
// - 3s when user is active, 30s when idle
// - SSE handles real-time updates, this is fallback/sync
useEffect(() => {
let lastActivity = Date.now();
let sseConnected = false;
// Track user activity
const handleActivity = () => { lastActivity = Date.now(); };
window.addEventListener('mousemove', handleActivity);
window.addEventListener('keydown', handleActivity);
const pollSystem = async () => {
try {
// UNIFIED ENDPOINT - 1 call instead of 4
const data = await api.get<any>('/v1/system/full-state');
// Update telemetry
if (data.telemetry) {
setMetrics(prev => ({
...prev,
activeAgents: data.orchestrator?.agentCount || 0,
agentsInVram: data.telemetry.agentsInVram || 0,
agentsInRam: data.telemetry.agentsInRam || 0,
jsHeapSize: data.telemetry.ram?.active ? data.telemetry.ram.active / (1024 * 1024) : 0,
vramUsage: (data.telemetry.gpu?.vramUsed && data.telemetry.gpu?.vramTotal)
? (data.telemetry.gpu.vramUsed / data.telemetry.gpu.vramTotal) * 100 : 0,
cpuTickDuration: data.telemetry.cpu || 0,
realCpu: data.telemetry.cpu || 0,
gpu: data.telemetry.gpu,
providerHealth: data.telemetry.providerHealth,
mediaQueue: data.telemetry.mediaQueue,
brain: data.telemetry.brain // [NEW] Unified Daemon cognitive data
}));
}
// Update agents
if (data.orchestrator?.agents) {
setAgents(data.orchestrator.agents);
}
// Update thoughts
if (data.introspection?.thoughts) {
setLiveThoughts(data.introspection.thoughts);
}
// Update projects for Dashboard Active Operations (VFS)
if (data.projects) {
setDashboardProjects(data.projects);
}
} catch (e) {
console.error("[POLL] Error (will retry):", e);
} finally {
// ADAPTIVE INTERVAL: 3s if active, 30s if idle (no activity for 30s)
const isIdle = (Date.now() - lastActivity) > 30000;
const interval = sseConnected ? 30000 : (isIdle ? 30000 : 3000);
timeoutId = setTimeout(pollSystem, interval);
}
};
let timeoutId = setTimeout(pollSystem, 1000); // Initial fetch
// SSE connection status
const handleSSEStatus = (connected: boolean) => { sseConnected = connected; };
return () => {
clearTimeout(timeoutId);
window.removeEventListener('mousemove', handleActivity);
window.removeEventListener('keydown', handleActivity);
};
}, []); // [NEURO-UPDATE] SSE BRIDGE (Server -> Client Bus)
useEffect(() => {
let evtSource: EventSource | null = null;
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
let reconnectDelay = 1000; // Start at 1s, exponential backoff up to 30s
let isCancelled = false;
function connectSSE() {
if (isCancelled) return;
console.log("[SSE] Connecting to Neural Uplink...");
evtSource = new EventSource(`/v1/factory/stream?apiKey=${DEFAULT_API_CONFIG.apiKey}`);
evtSource.onopen = () => {
console.log("[SSE] Connected.");
reconnectDelay = 1000; // Reset backoff on successful connection
};
evtSource.onmessage = (e) => {
try {
const data = JSON.parse(e.data);
if (data.type === 'bus_event') {
const innerEvent = data.payload;
if (innerEvent && innerEvent.type) {
systemBus.emit(innerEvent.type, innerEvent.payload, 'SERVER_BRIDGE');
}
} else if (data.type) {
systemBus.emit(data.type, data.payload, 'SERVER_BRIDGE');
if (data.type === SystemProtocol.TASK_COMPLETION) {
console.log("[SSE] Task Completed:", data.payload);
}
if (data.type === SystemProtocol.UI_REFRESH && data.payload?.uiCommand) {
const cmd = data.payload.uiCommand;
if (cmd.type === 'NAVIGATE') {
setActiveTab(cmd.destination);
} else if (cmd.type === 'ACTION') {
if (cmd.action === 'open_panel') {
if (cmd.panel === 'drive') setDriveOpen(true);
else if (cmd.panel === 'email') setEmailOpen(true);
} else if (cmd.action === 'close_panel') {
if (cmd.panel === 'drive') setDriveOpen(false);
else if (cmd.panel === 'email') setEmailOpen(false);
} else if (cmd.action === 'highlight' && cmd.target) {
const el = document.querySelector(cmd.target);
if (el) {
el.classList.add('silhouette-highlight');
setTimeout(() => el.classList.remove('silhouette-highlight'), cmd.durationMs || 3000);
}
}
}
}
}
} catch (err) {
// Ignore parse errors for heartbeat/keepalive messages
}
};
evtSource.onerror = () => {
if (isCancelled) return;
console.warn(`[SSE] Connection lost. Reconnecting in ${reconnectDelay / 1000}s...`);
evtSource?.close();
evtSource = null;
reconnectTimer = setTimeout(() => {
reconnectDelay = Math.min(reconnectDelay * 2, 30000); // Exponential backoff, max 30s
connectSSE();
}, reconnectDelay);
};
}
connectSSE();
return () => {
isCancelled = true;
if (reconnectTimer) clearTimeout(reconnectTimer);
evtSource?.close();
};
}, []);
const handleModeChange = (mode: SystemMode) => {
setMetrics(prev => ({ ...prev, currentMode: mode }));
localStorage.setItem('silhouette_power_mode', mode);
api.post('/v1/system/mode', { mode }).catch(console.error);
};
const handleIntrospectionChange = (layer: IntrospectionLayer) => {
setMetrics(prev => ({ ...prev, introspectionDepth: layer }));
localStorage.setItem('silhouette_introspection_depth', layer.toString());
api.post('/v1/introspection/layer', { layer }).catch(console.error);
};
const handleAgentThought = (agentId: string, thoughts: string[], role: string) => {
setSquadThoughts(prev => ({
...prev,
[agentId]: thoughts
}));
};
const handleCreateCampaign = () => {
const defaultName = `Campaign ${new Date().toLocaleDateString().replace(/\//g, '-')}`;
const name = prompt("SYSTEM PROTOCOL: INITIALIZE NEW CAMPAIGN\nEnter Project Identifier:", defaultName);
if (name) {
// Send request to server to create project
console.log("Creating campaign:", name);
}
};
// Track visited tabs to lazy-load components but keep them alive afterwards
const [visitedTabs, setVisitedTabs] = useState<Set<string>>(new Set(['dashboard']));
useEffect(() => {
setVisitedTabs(prev => {
const newSet = new Set(prev);
newSet.add(activeTab);
return newSet;
});
}, [activeTab]);
const renderContent = () => {
return (
<>
<div style={{ display: activeTab === 'dashboard' ? 'block' : 'none', height: '100%' }}>
{visitedTabs.has('dashboard') && <Dashboard metrics={metrics} projects={dashboardProjects} onCreateProject={handleCreateCampaign} />}
</div>
<div style={{ display: activeTab === 'system_control' ? 'block' : 'none', height: '100%' }}>
{visitedTabs.has('system_control') && (
<SystemControl
metrics={metrics}
setMode={handleModeChange}
autonomyConfig={autonomyConfig}
setAutonomyConfig={setAutonomyConfig}
/>
)}
</div>
<div style={{ display: activeTab === 'orchestrator' ? 'block' : 'none', height: '100%' }}>
{visitedTabs.has('orchestrator') && <AgentOrchestrator agents={agents} currentStage={metrics.currentStage} squadThoughts={squadThoughts} />}
</div>
<div style={{ display: activeTab === 'introspection' ? 'block' : 'none', height: '100%' }}>
{visitedTabs.has('introspection') && (
<IntrospectionHub />
)}
</div>
<div style={{ display: activeTab === 'visual_cortex' ? 'block' : 'none', height: '100%' }}>
{visitedTabs.has('visual_cortex') && (
<React.Suspense fallback={<div className="flex items-center justify-center h-full text-cyan-400">Loading Visual Cortex...</div>}>
<NexusCanvas />
</React.Suspense>
)}
</div>
<div style={{ display: activeTab === 'memory' ? 'block' : 'none', height: '100%' }}>
{visitedTabs.has('memory') && <ContinuumMemoryExplorer />}
</div>
<div style={{ display: activeTab === 'dynamic_workspace' ? 'block' : 'none', height: '100%' }}>
{visitedTabs.has('dynamic_workspace') && <DynamicWorkspace initialProjectId={pendingProjectId} />}
</div>
<div style={{ display: activeTab === 'media_studio' ? 'block' : 'none', height: '100%' }}>
{visitedTabs.has('media_studio') && (
<React.Suspense fallback={<div className="flex items-center justify-center h-full text-cyan-400">Loading Neural Engine...</div>}>
<MediaStudio />
</React.Suspense>
)}
</div>
<div style={{ display: activeTab === 'settings' ? 'block' : 'none', height: '100%' }}>
{visitedTabs.has('settings') && <Settings />}
</div>
<div style={{ display: activeTab === 'terminal' ? 'block' : 'none', height: '100%' }}>
{visitedTabs.has('terminal') && <TerminalLog logs={logs} />}
</div>
</>
);
};
const mode = uiOverride?.mode === 'DEFENSE' ? 'dark' : (uiOverride?.mode === 'FLOW' ? 'cyberpunk' : (appSettings.theme?.mode || 'dark'));
const density = uiOverride?.density || (appSettings.theme?.density || 'comfortable');
const borderClass = uiOverride?.mode === 'DEFENSE' ? 'border-4 border-red-900' : '';
const paddingClass = density === 'compact' ? 'p-4' : 'p-8';
return (
<div className={`flex h-screen bg-slate-950 overflow-hidden relative ${mode} ${borderClass}`}>
<ProtocolOverlay />
{/* HEADLESS SENSORS - Wrapped in Suspense */}
<Suspense fallback={null}>
<VisualCortex />
</Suspense>
<Suspense fallback={null}>
<ChatWidget
currentUserRole={currentUserRole}
onChangeRole={setCurrentUserRole}
systemMetrics={metrics}
onUpdateThoughts={setLiveThoughts}
onAgentThought={handleAgentThought}
/>
</Suspense>
<Sidebar
activeTab={activeTab}
setActiveTab={(tab) => {
setActiveTab(tab);
setIsMobileMenuOpen(false); // Close on mobile after click
}}
isMobileOpen={isMobileMenuOpen}
onCloseMobile={() => setIsMobileMenuOpen(false)}
onDriveClick={() => setDriveOpen(true)}
onEmailClick={() => setEmailOpen(true)}
/>
<main className={`flex-1 ${paddingClass} overflow-y-auto relative pt-16 md:pt-8 w-full`}>
{/* Mobile Header */}
<div className="md:hidden fixed top-0 left-0 right-0 h-16 bg-slate-950/80 backdrop-blur border-b border-cyan-900/50 z-30 flex items-center justify-between px-4">
<div className="font-bold text-cyan-400 tracking-wider">SILHOUETTE</div>
<button
onClick={() => setIsMobileMenuOpen(true)}
className="p-2 text-cyan-400 hover:bg-cyan-900/30 rounded"
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16m-7 6h7" />
</svg>
</button>
</div>
{/* Notification Center in mt-mobile to avoid overlapping Header */}
<div className="absolute top-20 md:top-4 right-4 z-40">
<NotificationCenter />
</div>
<div className="absolute top-16 md:top-0 left-0 w-full h-1 bg-gradient-to-r from-cyan-500 via-purple-500 to-cyan-500 opacity-50"></div>
<Suspense fallback={
<div className="flex items-center justify-center h-full text-cyan-400">
Loading module...
</div>
}>
{renderContent()}
</Suspense>
</main>
{/* Drive Panel (Lazy Loaded) */}
<Suspense fallback={null}>
<DrivePanel isOpen={driveOpen} onClose={() => setDriveOpen(false)} />
</Suspense>
{/* Email Panel (Lazy Loaded) */}
<Suspense fallback={null}>
<EmailPanel isOpen={emailOpen} onClose={() => setEmailOpen(false)} />
</Suspense>
{/* Onboarding Tour */}
<OnboardingTour />
</div>
);
};
export default App;