File size: 16,868 Bytes
adfa6d0
 
 
55f6497
035ec20
 
a9df765
adfa6d0
 
39e9c8d
adfa6d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
035ec20
 
39e9c8d
 
adfa6d0
035ec20
adfa6d0
 
 
 
44bc537
adfa6d0
 
 
a9df765
adfa6d0
23da5af
adfa6d0
 
 
 
44bc537
52cade9
66db342
52cade9
adfa6d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40d5860
adfa6d0
40d5860
adfa6d0
 
40d5860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adfa6d0
 
 
 
40d5860
adfa6d0
 
 
 
 
 
 
 
 
 
 
 
6e94481
a9df765
adfa6d0
 
 
 
32892af
adfa6d0
035ec20
adfa6d0
035ec20
7e9698c
adfa6d0
 
 
 
 
44bc537
 
 
52cade9
44bc537
 
 
9030c9b
44bc537
 
 
adfa6d0
 
44bc537
adfa6d0
807931e
7abcf9e
 
807931e
 
 
 
adfa6d0
 
 
 
 
 
 
 
 
 
 
e0ec3d2
adfa6d0
 
 
e0ec3d2
 
 
 
 
adfa6d0
 
 
 
 
 
e0ec3d2
 
 
adfa6d0
 
a9df765
035ec20
39e9c8d
adfa6d0
 
 
40d5860
adfa6d0
 
 
 
40d5860
adfa6d0
 
 
 
 
 
 
 
 
 
52cade9
39e9c8d
 
adfa6d0
 
 
 
44bc537
 
 
 
 
 
 
 
adfa6d0
44bc537
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adfa6d0
 
44bc537
adfa6d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9df765
39e9c8d
adfa6d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55f6497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adfa6d0
 
55f6497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adfa6d0
 
e0ec3d2
adfa6d0
 
 
 
 
 
e0ec3d2
adfa6d0
 
 
 
 
035ec20
40d5860
 
 
 
 
 
 
 
 
 
e0ec3d2
39e9c8d
adfa6d0
 
 
 
 
 
52cade9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39e9c8d
a9df765
035ec20
a9df765
 
035ec20
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
432
import { useEffect, useState, useRef } from 'react';
import ForceGraph3D from 'react-force-graph-3d';
import * as THREE from 'three';
import SpriteText from 'three-spritetext';
import { apiFetch } from '../api';
import './KnowledgeGraph.css';

// Stunning conceptual mock graph representing SOMA's cognitive architecture
const MOCK_GRAPH = {
  nodes: [
    { id: 'SOMA', label: 'SOMA (Core)', connections: 10, type: 'core' },
    { id: 'Cortex', label: 'Cortex Layer', connections: 8, type: 'core' },
    { id: 'Thalamus', label: 'Thalamus (Routing)', connections: 6, type: 'entity' },
    { id: 'Hippocampus', label: 'Hippocampus', connections: 7, type: 'entity' },
    { id: 'Neocortex', label: 'Neocortex', connections: 6, type: 'entity' },
    { id: 'Sensory Cortex', label: 'Sensory Cortex', connections: 4, type: 'concept' },
    { id: 'Working Memory', label: 'Working Memory', connections: 5, type: 'concept' },
    { id: 'Episodic Memory', label: 'Episodic Memory', connections: 4, type: 'concept' },
    { id: 'Sleep Cycle', label: 'Sleep Cycle', connections: 3, type: 'method' },
    { id: 'Neural Inscription', label: 'Inscription Layer', connections: 3, type: 'method' },
    { id: 'Llama 3.1', label: 'Llama 3.1', connections: 3, type: 'metric' },
    { id: 'Groq API', label: 'Groq API', connections: 2, type: 'metric' }
  ],
  links: [
    { source: 'SOMA', target: 'Cortex', label: 'ORCHESTRATES' },
    { source: 'SOMA', target: 'Neural Inscription', label: 'ACCEPTS' },
    { source: 'Cortex', target: 'Thalamus', label: 'ROUTES_BY' },
    { source: 'Cortex', target: 'Hippocampus', label: 'CONSOLIDATES' },
    { source: 'Cortex', target: 'Neocortex', label: 'STORES_IN' },
    { source: 'Sensory Cortex', target: 'Hippocampus', label: 'WRITES_TO' },
    { source: 'Working Memory', target: 'Thalamus', label: 'SYNCS_WITH' },
    { source: 'Episodic Memory', target: 'Hippocampus', label: 'LOGS_IN' },
    { source: 'Sleep Cycle', target: 'Hippocampus', label: 'OPTIMIZES' },
    { source: 'Sleep Cycle', target: 'Neocortex', label: 'REINFORCES' },
    { source: 'Cortex', target: 'Llama 3.1', label: 'COMPUTES' },
    { source: 'Llama 3.1', target: 'Groq API', label: 'HOSTED_ON' }
  ]
};

function KnowledgeGraph({ refreshTick }) {
  const [graphData, setGraphData] = useState({ nodes: [], links: [] });
  const [loading, setLoading] = useState(true);
  const [dbStatus, setDbStatus] = useState('connecting');
  const [dimensions, setDimensions] = useState({ width: 800, height: 500 });
  const [stats, setStats] = useState({ node_count: 0, edge_count: 0, top_entities: [] });
  const [physicsActive, setPhysicsActive] = useState(true);
  const [hudCollapsed, setHudCollapsed] = useState(false);
  
  const containerRef = useRef(null);
  const fgRef = useRef();

  // Measure container dimensions to auto-resize the canvas
  useEffect(() => {
    if (!containerRef.current) return;
    const resizeObserver = new ResizeObserver((entries) => {
      for (let entry of entries) {
        const { width, height } = entry.contentRect;
        const isMobile = window.innerWidth < 768;
        const adjustedWidth = isMobile ? (window.innerWidth - 32) : width;
        const adjustedHeight = isMobile ? 700 : height;
        setDimensions({ width: adjustedWidth || 800, height: adjustedHeight || 500 });
      }
    });
    resizeObserver.observe(containerRef.current);
    return () => resizeObserver.disconnect();
  }, []);

  // Fetch graph database from backend
  const fetchGraph = async () => {
    setLoading(true);
    try {
      const res = await apiFetch('/api/v1/graph');
      if (!res.ok) {
        throw new Error('Graph fetch returned unhealthy status');
      }
      
      const data = await res.json();
      
      if (data.status === 'offline' || data.status === 'error') {
        setDbStatus(data.status || 'offline');
        setGraphData({ nodes: [], links: [] });
      } else {
        setDbStatus('online');
        if (!data.nodes || data.nodes.length === 0) {
          setGraphData({ nodes: [], links: [] });
        } else {
          const nodes = data.nodes.map(n => ({
            id: n.id,
            label: n.label || n.id,
            connections: n.connections || 1,
            type: 'entity'
          }));
          
          const links = data.edges.map(e => ({
            source: e.source,
            target: e.target,
            label: e.label || 'RELATED_TO'
          }));
          
          setGraphData({ nodes, links });
        }
      }
    } catch (error) {
      console.error('Graph fetch failed', error);
      setDbStatus('offline');
      setGraphData({ nodes: [], links: [] });
    } finally {
      setLoading(false);
    }
  };

  const fetchStats = async () => {
    try {
      const res = await apiFetch('/api/v1/graph/stats');
      if (res.ok) {
        const data = await res.json();
        if (data.status === 'online') {
          setStats(data);
        }
      }
    } catch (err) {
      console.error('Stats fetch failed', err);
    }
  };

  useEffect(() => {
    fetchGraph();
    fetchStats();
  }, [refreshTick]);

  // Physics force configurations to pull the neural cluster into a tight, brain-like shape
  useEffect(() => {
    if (fgRef.current) {
      const d3Force = fgRef.current.d3Force;
      if (d3Force) {
        d3Force('charge').strength(-20).distanceMax(100);
        d3Force('link').distance(30);
        
        // Custom gravity force to pull unconnected clusters to the center
        d3Force('gravity', (alpha) => {
          graphData.nodes.forEach(node => {
            node.vx = (node.vx || 0) + (0 - node.x) * 0.05 * alpha;
            node.vy = (node.vy || 0) + (0 - node.y) * 0.05 * alpha;
            node.vz = (node.vz || 0) + (0 - node.z) * 0.05 * alpha;
          });
        });
      }
      
      // Auto-fit camera with appropriate padding to ensure complete visibility
      setTimeout(() => {
        if (window.innerWidth < 768) {
          // Shift camera down on mobile to make objects at (0,0,0) appear higher (reduced shift)
          fgRef.current.cameraPosition({ x: 0, y: -80, z: 300 }, { x: 0, y: -80, z: 0 }, 600);
        } else {
          const padding = 20;
          fgRef.current.zoomToFit(800, padding);
        }
      }, 600);
    }
  }, [graphData]);

  // Calculate max connections dynamically to scale color thresholds
  const maxConnections = graphData.nodes && graphData.nodes.length > 0
    ? Math.max(...graphData.nodes.map(n => n.connections || 1), 1)
    : 1;

  // Color mapper based on node type & degree
  const getNodeColor = (node) => {
    if (node.id === 'SOMA') return '#ff6b35'; // Core Hub is SOMA Orange
    
    // For offline/mock mode, retain the pre-assigned structural category colors
    if (dbStatus !== 'online') {
      if (node.type === 'core') return '#ff6b35'; // Orange
      if (node.type === 'method') return '#ff8b54'; // Soft Orange
      if (node.type === 'concept') return '#ffa67c'; // Pale Orange
      if (node.type === 'metric') return '#a3a3a3'; // Neutral Grey
      return '#737373'; // Darker Grey
    }
    
    // For live Neo4j data, dynamically scale colors based on relative synaptic density!
    const connections = node.connections || 1;
    const ratio = connections / maxConnections;
    
    if (ratio >= 0.8) return '#ff6b35'; // High centrality (Orange)
    if (ratio >= 0.4) return '#ff9c7a'; // Medium centrality (Soft Orange)
    return '#a3a3a3'; // Low centrality (Silver/Grey)
  };

  return (
    <div className="graph-stage fade-in">
      <div className="graph-toolbar">
        <div className="graph-title-block">
          <button className="graph-select">
            <span className="material-icons">hub</span>
            <span>{dbStatus === 'online' ? 'Real-time 3D Neo4j Graph' : '3D SOMA Cognitive Memory Mesh'}</span>
          </button>
          {dbStatus !== 'online' && (
            <span className="db-status-badge warning pulse">
              <span className="dot" />
              Neo4j Database Offline
            </span>
          )}
          {dbStatus === 'online' && (
            <span className="db-status-badge success">
              <span className="dot" />
              Neo4j Synchronized (Live)
            </span>
          )}
        </div>


      </div>

      <div className="graph-network-container" ref={containerRef}>
        {/* Live Telemetry HUD Overlay */}
        <div className="graph-hud-overlay">
          <div className="hud-panel">
            <div className="hud-header" style={{display: 'flex', justifyContent: 'space-between', width: '100%', alignItems: 'center'}}>
              <div style={{display: 'flex', alignItems: 'center', gap: '8px'}}>
                <span className="material-icons">analytics</span>
                <span>Semantic Telemetry</span>
              </div>
              <span className="material-icons" style={{cursor: 'pointer', fontSize: '20px', color: '#ff6b35'}} onClick={() => setHudCollapsed(!hudCollapsed)}>
                {hudCollapsed ? 'expand_more' : 'expand_less'}
              </span>
            </div>
            {!hudCollapsed && (
              <>
                <div className="hud-row">
                  <span className="hud-label">Nodes:</span>
                  <span className="hud-value">{dbStatus === 'online' ? stats.node_count : graphData.nodes.length}</span>
                </div>
                <div className="hud-row">
                  <span className="hud-label">Synapses:</span>
                  <span className="hud-value">{dbStatus === 'online' ? stats.edge_count : graphData.links.length}</span>
                </div>
                <div className="hud-row">
                  <span className="hud-label">Storage:</span>
                  <span className="hud-value status-glow">{dbStatus === 'online' ? 'LTM (Neo4j)' : 'STM (Cache)'}</span>
                </div>
              </>
            )}
          </div>
          
          {!hudCollapsed && dbStatus === 'online' && stats.top_entities && stats.top_entities.length > 0 && (
            <div className="hud-panel top-entities">
              <div className="hud-header">
                <span className="material-icons">star</span>
                <span>Primary Hubs</span>
              </div>
              <div className="hud-entity-list">
                {stats.top_entities.map((ent, idx) => (
                  <div key={idx} className="hud-entity-row">
                    <span className="entity-rank">#{idx+1}</span>
                    <span className="entity-name">{ent.entity}</span>
                    <span className="entity-connections">{ent.connections} rx</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        <ForceGraph3D
          ref={fgRef}
          graphData={graphData}
          width={dimensions.width}
          height={dimensions.height}
          backgroundColor="rgba(0, 0, 0, 0)" // Glassmorphic translucent rendering
          
          // Render gorgeous glowing 3D spheres with emissive materials (100% stable!)
          nodeThreeObject={node => {
            const size = Math.max(3.2, Math.min(node.connections * 1.6, 9.5)); // Perfectly scaled spheres
            const geom = new THREE.SphereGeometry(size, 24, 24);
            const mat = new THREE.MeshLambertMaterial({
              color: getNodeColor(node),
              transparent: true,
              opacity: 0.95,
              emissive: getNodeColor(node),
              emissiveIntensity: 0.45
            });
            const sphere = new THREE.Mesh(geom, mat);

            // Always-visible name tag floating above the sphere
            const tag = new SpriteText((node.label || node.id).toUpperCase());
            tag.color = getNodeColor(node);
            tag.textHeight = 3.2;
            tag.fontWeight = '700';
            tag.backgroundColor = 'rgba(10, 10, 10, 0.55)';
            tag.padding = 1.2;
            tag.borderRadius = 2;
            tag.position.y = size + 4;
            tag.material.depthWrite = false; // keep tag readable through overlapping geometry

            const group = new THREE.Group();
            group.add(sphere);
            group.add(tag);
            return group;
          }}
          
          // Always-visible relationship tag floating at the middle of each link
          linkThreeObjectExtend={true}
          linkThreeObject={link => {
            const tag = new SpriteText((link.label || 'RELATED_TO').toUpperCase());
            tag.color = '#ff9c7a';
            tag.textHeight = 2.2;
            tag.fontWeight = '700';
            tag.backgroundColor = 'rgba(10, 10, 10, 0.45)';
            tag.padding = 1;
            tag.borderRadius = 2;
            tag.material.depthWrite = false;
            return tag;
          }}
          linkPositionUpdate={(sprite, { start, end }) => {
            sprite.position.set(
              start.x + (end.x - start.x) / 2,
              start.y + (end.y - start.y) / 2,
              start.z + (end.z - start.z) / 2
            );
          }}
          
          nodeRelSize={3}
          linkColor={() => 'rgba(255, 107, 53, 0.25)'} // Soft, clean axon link fibers
          linkWidth={1.8} // Sleek link line thickness
          
          // Glowing Thought Flows (sliding directional particles along axons)
          linkDirectionalParticles={3}
          linkDirectionalParticleSpeed={0.006}
          linkDirectionalParticleWidth={1.5}
          linkDirectionalParticleColor={() => '#ff6b35'}
          
          showNavInfo={false}
          enablePointerInteraction={true}
          enableNodeDrag={true}
        />
        
        {graphData.nodes.length === 0 && !loading && (
          <div className="graph-empty-state">
            <span className="material-icons empty-icon pulse">bubble_chart</span>
            <h3>Neural Mesh Empty</h3>
            <p>
              Your cognitive space is completely clean. Start chatting with SOMA or submit a sensory inscription to build your memory graph!
            </p>
          </div>
        )}

        {/* Legend removed per user request */}

        {loading && (
          <div className="graph-loading">
            <span className="material-icons pulse">refresh</span>
            <span>Synchronizing cognitive mesh...</span>
          </div>
        )}

        <div className="graph-actions">
          <button 
            className="graph-icon-button" 
            onClick={() => {
              if (fgRef.current) fgRef.current.zoomToFit(600, 20);
            }}
            title="Recenter Camera"
          >
            <span className="material-icons">zoom_out_map</span>
          </button>
          <button 
            className="graph-icon-button" 
            onClick={() => {
              if (fgRef.current) {
                const currentPos = fgRef.current.cameraPosition();
                fgRef.current.cameraPosition(
                  { x: currentPos.x * 0.75, y: currentPos.y * 0.75, z: currentPos.z * 0.75 },
                  null,
                  300
                );
              }
            }}
            title="Zoom In"
          >
            <span className="material-icons">zoom_in</span>
          </button>
          <button 
            className="graph-icon-button" 
            onClick={() => {
              if (fgRef.current) {
                const currentPos = fgRef.current.cameraPosition();
                fgRef.current.cameraPosition(
                  { x: currentPos.x * 1.35, y: currentPos.y * 1.35, z: currentPos.z * 1.35 },
                  null,
                  300
                );
              }
            }}
            title="Zoom Out"
          >
            <span className="material-icons">zoom_out</span>
          </button>
          <button 
            className="graph-icon-button" 
            onClick={() => {
              const newActive = !physicsActive;
              setPhysicsActive(newActive);
              if (fgRef.current) {
                if (physicsActive) {
                  fgRef.current.d3PauseSimulation();
                } else {
                  fgRef.current.d3ResumeSimulation();
                }
              }
            }}
            title={physicsActive ? "Pause Simulation" : "Resume Simulation"}
          >
            <span className="material-icons">{physicsActive ? "pause" : "play_arrow"}</span>
          </button>
          <button 
            className="graph-icon-button" 
            onClick={() => {
              fetchGraph();
              fetchStats();
            }}
            title="Sync Mesh"
          >
            <span className="material-icons">sync</span>
          </button>
        </div>
      </div>
    </div>
  );
}

export default KnowledgeGraph;