Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
feat(ui): complete graph visualization overhaul
ZohaibHassan1698a2cf9490bd
diff --git a/semantica-explorer/src/workspaces/GraphWorkspace/GraphCanvas.tsx b/semantica-explorer/src/workspaces/GraphWorkspace/GraphCanvas.tsxindex c2618c89..7cf3f1a3 100644--- a/semantica-explorer/src/workspaces/GraphWorkspace/GraphCanvas.tsx+++ b/semantica-explorer/src/workspaces/GraphWorkspace/GraphCanvas.tsx@@ -1,13 +1,14 @@/*** src/workspaces/GraphWorkspace/GraphCanvas.tsx*/-import { useEffect, useRef, useCallback } from "react";+import { useEffect, useRef, useState, useCallback } from "react";import Sigma from "sigma";import FA2Layout from "graphology-layout-forceatlas2/worker";import { graph } from "../../store/graphStore";export interface GraphCanvasProps {onNodeClick: (nodeId: string) => void;+ selectedNodeId: string;isLayoutRunning: boolean;className?: string;}@@ -32,11 +33,13 @@ const SIGMA_SETTINGS = {webGLTarget: "webgl2" as const,};-export function GraphCanvas({ onNodeClick, isLayoutRunning, className }: GraphCanvasProps) {+export function GraphCanvas({ onNodeClick, selectedNodeId, isLayoutRunning, className }: GraphCanvasProps) {const containerRef = useRef<HTMLDivElement>(null);const sigmaRef = useRef<Sigma | null>(null);const fa2Ref = useRef<FA2Layout | null>(null);++ const [hoveredNode, setHoveredNode] = useState<string | null>(null);useEffect(() => {if (!containerRef.current || sigmaRef.current) return;@@ -49,21 +52,20 @@ export function GraphCanvas({ onNodeClick, isLayoutRunning, className }: GraphCa}});resizeObserver.observe(containerRef.current);-+ // Click Eventssigma.on("clickNode", ({ node }) => {onNodeClick(node);- graph.setNodeAttribute(node, "highlighted", true);- graph.forEachNode((n) => {- if (n !== node) graph.setNodeAttribute(n, "highlighted", false);- });});sigma.on("clickStage", () => {onNodeClick("");- graph.forEachNode((n) => graph.setNodeAttribute(n, "highlighted", false));});+ // Hover Events+ sigma.on("enterNode", ({ node }) => setHoveredNode(node));+ sigma.on("leaveNode", () => setHoveredNode(null));+return () => {resizeObserver.disconnect();sigma.kill();@@ -71,6 +73,75 @@ export function GraphCanvas({ onNodeClick, isLayoutRunning, className }: GraphCa};}, [onNodeClick]);+++ useEffect(() => {+ const sigma = sigmaRef.current;+ if (!sigma) return;+++ const activeNode = hoveredNode || selectedNodeId;+++ const isValidActiveNode = activeNode && graph.hasNode(activeNode);+++ const activeNeighbors = isValidActiveNode ? new Set(graph.neighbors(activeNode)) : new Set();++ if (!isValidActiveNode) {++ sigma.setSetting("nodeReducer", undefined);++ sigma.setSetting("edgeReducer", (edge, data) => ({+ ...data,+ color: "#161b22",+ size: Math.max(0.5, (data.size || 1) * 0.5),+ zIndex: 0,+ }));+ } else {+ sigma.setSetting("nodeReducer", (node, data) => {+ const isFocused = node === activeNode;+ const isNeighbor = activeNeighbors.has(node);++ if (isFocused || isNeighbor) {+ return {+ ...data,+ zIndex: isFocused ? 2 : 1,+ borderColor: isFocused ? "#ffffff" : data.borderColor,+ borderSize: isFocused ? 2 : data.borderSize,+ };+ }++ // Mute all other nodes into the background+ return {+ ...data,+ color: "#1c2128",+ borderColor: "#0d1117",+ label: "",+ zIndex: 0,+ };+ });++ sigma.setSetting("edgeReducer", (edge, data) => {++ if (graph.hasExtremity(edge, activeNode)) {+ return {+ ...data,+ color: "#58a6ff",+ size: (data.size || 1) * 2,+ zIndex: 1,+ };+ }++ return { ...data, hidden: true };+ });+ }++ sigma.refresh();+ }, [hoveredNode, selectedNodeId]);+++useEffect(() => {if (isLayoutRunning) {if (!fa2Ref.current) {@@ -87,17 +158,18 @@ export function GraphCanvas({ onNodeClick, isLayoutRunning, className }: GraphCa};}, [isLayoutRunning]);+const handleFitView = useCallback(() => {sigmaRef.current?.getCamera().animatedReset({ duration: 500 });}, []);return (<div style={{ position: "relative", width: "100%", height: "100%" }}>- <div ref={containerRef} className={className} style={{ width: "100%", height: "100%", background: "#0d1117" }} />+ <div ref={containerRef} className={className} style={{ width: "100%", height: "100%", background: "transparent" }} /><buttononClick={handleFitView}style={{- position: "absolute", bottom: 16, right: 16, padding: "8px 16px",+ position: "absolute", bottom: 24, left: 24, padding: "8px 16px",background: "#1f6feb", color: "#fff", border: "none", borderRadius: 6,cursor: "pointer", fontWeight: 600, zIndex: 10,}}diff --git a/semantica-explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx b/semantica-explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsxindex 1a774caa..07b79235 100644--- a/semantica-explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx+++ b/semantica-explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx@@ -1,138 +1,192 @@/*** src/workspaces/GraphWorkspace/GraphWorkspace.tsx*/-import { useState, useCallback } from "react";import { GraphCanvas } from "./GraphCanvas";import { useLoadGraph, useReloadGraph } from "./useLoadGraph";import { graph } from "../../store/graphStore";-// ─── Node Properties Side Panel ────────────────────────────────────────────+const HUD_CSS = `+ .palantir-bg {+ background: radial-gradient(ellipse at center, #0d1117 0%, #010409 100%);+ }+ .palantir-grid {+ position: absolute;+ inset: 0;+ background-image:+ linear-gradient(rgba(88, 166, 255, 0.05) 1px, transparent 1px),+ linear-gradient(90deg, rgba(88, 166, 255, 0.05) 1px, transparent 1px);+ background-size: 40px 40px;+ pointer-events: none;+ z-index: 1;+ }+ .palantir-vignette {+ position: absolute;+ inset: 0;+ background: radial-gradient(ellipse at center, transparent 30%, rgba(1, 4, 9, 0.85) 100%);+ pointer-events: none;+ z-index: 2;+ }+ .glass-header {+ background: linear-gradient(180deg, rgba(13,17,23,0.85) 0%, rgba(13,17,23,0) 100%);+ border-bottom: 1px solid rgba(88,166,255,0.1);+ backdrop-filter: blur(8px);+ -webkit-backdrop-filter: blur(8px);+ }+ .glass-hud {+ background: linear-gradient(135deg, rgba(13,17,23,0.75), rgba(22,27,34,0.6));+ backdrop-filter: blur(16px) saturate(1.2);+ -webkit-backdrop-filter: blur(16px) saturate(1.2);+ border-left: 1px solid rgba(88,166,255,0.2);+ box-shadow: -8px 0 32px rgba(0,0,0,0.5), inset 1px 0 0 rgba(255,255,255,0.05);+ }+ .hud-scrollbar::-webkit-scrollbar { width: 4px; }+ .hud-scrollbar::-webkit-scrollbar-track { background: transparent; }+ .hud-scrollbar::-webkit-scrollbar-thumb { background: rgba(88, 166, 255, 0.3); border-radius: 4px; }+`;+function NodePanel({ nodeId }: { nodeId: string }) {if (!nodeId) {return (- <aside style={panelStyle}>- <p style={{ color: "#8b949e", fontSize: 13, marginTop: 20, textAlign: "center" }}>- Click a node to inspect its properties.+ <div style={{ padding: "32px 24px", textAlign: "center" }}>+ <p style={{ color: "#8b949e", fontSize: 14, margin: 0 }}>+ Select a node to view details</p>- </aside>+ </div>);}- // Read directly from the graphology singleton!- // We NEVER put the 50k nodes into React state to do this lookup.const attrs = graph.getNodeAttributes(nodeId);return (- <aside style={panelStyle}>- <h3 style={{ margin: "0 0 12px", color: "#e6edf3", fontSize: 16 }}>- {String(attrs?.label ?? nodeId)}- </h3>-- <div style={{ marginBottom: 16 }}>- <span style={{- background: attrs?.color || "#6c8ebf",- color: "#fff",- padding: "2px 8px",- borderRadius: 12,- fontSize: 11,- fontWeight: "bold"- }}>- {attrs?.nodeType || "Entity"}- </span>+ <aside style={{ padding: 24 }}>+ <div style={{ borderBottom: "1px solid rgba(88, 166, 255, 0.2)", paddingBottom: 16, marginBottom: 20 }}>+ <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>+ <span style={{+ background: attrs?.color || "#6c8ebf",+ boxShadow: `0 0 10px ${attrs?.color || "#6c8ebf"}`,+ width: 8, height: 8, borderRadius: "50%", display: "inline-block"+ }} />+ <span style={{ color: attrs?.color || "#6c8ebf", fontSize: 12, fontWeight: 600 }}>+ {attrs?.nodeType || "Entity"}+ </span>+ </div>+ <h3 style={{ margin: 0, color: "#ffffff", fontSize: 20, fontWeight: 600 }}>+ {String(attrs?.label ?? nodeId)}+ </h3></div>- <table style={{ width: "100%", fontSize: 12, borderCollapse: "collapse" }}>- <tbody>- {/* Render standard attributes safely */}- {Object.entries(attrs?.properties || {}).map(([k, v]) => (- <tr key={k} style={{ borderBottom: "1px solid #21262d" }}>- <td style={{ color: "#8b949e", padding: "6px 8px 6px 0", fontWeight: 600 }}>{k}</td>- <td style={{ color: "#e6edf3", padding: "6px 0", wordBreak: "break-word" }}>- {typeof v === "object" ? JSON.stringify(v) : String(v)}- </td>- </tr>- ))}- </tbody>- </table>+ <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>+ {Object.entries(attrs?.properties || {}).map(([k, v]) => (+ <div key={k} style={{ background: "rgba(0,0,0,0.2)", padding: "10px 14px", borderRadius: 6, border: "1px solid rgba(255,255,255,0.05)" }}>+ <div style={{ color: "rgba(88, 166, 255, 0.7)", fontSize: 11, marginBottom: 4 }}>+ {k}+ </div>+ <div style={{ color: "#e6edf3", fontSize: 13, fontFamily: "monospace", wordBreak: "break-word" }}>+ {typeof v === "object" ? JSON.stringify(v) : String(v)}+ </div>+ </div>+ ))}+ </div></aside>);}-// ─── Main Workspace Component ──────────────────────────────────────────────export function GraphWorkspace() {- // THE ONLY REACT STATE FOR THE GRAPHconst [selectedNodeId, setSelectedNodeId] = useState<string>("");const [isLayoutRunning, setIsLayoutRunning] = useState(false);-const reload = useReloadGraph();- // Stable callback to prevent unnecessary re-rendersconst handleNodeClick = useCallback((nodeId: string) => {setSelectedNodeId(nodeId);}, []);- // Fetch data into the mutable singletonconst { data: summary, isLoading, isError, error } = useLoadGraph({enabled: true,onGraphReady: () => {- // Auto-start the ForceAtlas2 layout once data finishes downloadingsetIsLayoutRunning(true);},});return (- <div style={rootStyle}>- {/* ── Toolbar ─────────────────────────────────────────────────── */}- <header style={headerStyle}>- <div style={{ display: "flex", gap: 12, alignItems: "center" }}>- <h2 style={{ margin: 0, fontSize: 16, color: "#e6edf3" }}>Graph Explorer</h2>-- {isLoading && <span style={{ color: "#8b949e", fontSize: 13 }}>Fetching graph data...</span>}- {summary && (- <span style={{ color: "#8b949e", fontSize: 13 }}>- {summary.nodeCount.toLocaleString()} nodes · {summary.edgeCount.toLocaleString()} edges- </span>- )}- {isError && (- <span style={{ color: "#f85149", fontSize: 13 }}>Error: {(error as Error).message}</span>- )}- </div>- <div style={{ display: "flex", gap: 8 }}>- <button- onClick={() => setIsLayoutRunning((v) => !v)}- style={btnStyle(isLayoutRunning ? "#388bfd" : "#21262d", isLayoutRunning ? "#fff" : "#e6edf3")}- disabled={isLoading}- >- {isLayoutRunning ? "⏸ Pause Layout" : "▶ Run Layout"}- </button>- <button onClick={reload} style={btnStyle("#21262d", "#e6edf3")} disabled={isLoading}>- ↺ Reload Graph- </button>- </div>- </header>-- {/* ── Main Layout ──────────────────────────────────────────────── */}- <main style={mainStyle}>- {/* WebGL Canvas Area */}- <div style={{ flex: 1, minWidth: 0, height: "100%", position: "relative" }}>- <GraphCanvas- onNodeClick={handleNodeClick}- isLayoutRunning={isLayoutRunning}- />- </div>+ <div className="palantir-bg" style={{ position: "relative", width: "100%", height: "100%", overflow: "hidden" }}>+ <style>{HUD_CSS}</style>++ <div className="palantir-grid" />+ <div className="palantir-vignette" />++ <div style={{ position: "absolute", inset: 0, zIndex: 3 }}>+ <GraphCanvas+ onNodeClick={handleNodeClick}+ selectedNodeId={selectedNodeId}+ isLayoutRunning={isLayoutRunning}+ />+ </div>++ <div style={{ position: "absolute", inset: 0, pointerEvents: "none", zIndex: 10 }}>++ <header className="glass-header" style={{ pointerEvents: "auto", display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 24px" }}>+ <div style={{ display: "flex", gap: 16, alignItems: "center" }}>+ <h2 style={{ margin: 0, fontSize: 18, color: "#ffffff", fontWeight: 600 }}>Graph Explorer</h2>++ {isLoading && <span style={{ color: "rgba(88,166,255,0.8)", fontSize: 13 }}>Loading data...</span>}+ {summary && (+ <span style={{ background: "rgba(88,166,255,0.1)", color: "#58a6ff", padding: "4px 10px", borderRadius: 4, fontSize: 12, border: "1px solid rgba(88,166,255,0.2)" }}>+ {summary.nodeCount.toLocaleString()} nodes · {summary.edgeCount.toLocaleString()} edges+ </span>+ )}+ {isError && (+ <span style={{ color: "#ff7b72", fontSize: 13 }}>Error: {(error as Error).message}</span>+ )}+ </div>++ <div style={{ display: "flex", gap: 12 }}>+ <button+ onClick={() => setIsLayoutRunning((v) => !v)}+ style={btnStyle(isLayoutRunning ? "rgba(56, 139, 253, 0.15)" : "rgba(255,255,255,0.05)", isLayoutRunning ? "#58a6ff" : "#e6edf3")}+ disabled={isLoading}+ >+ <span style={{ display: "inline-block", width: 8, height: 8, borderRadius: "50%", background: isLayoutRunning ? "#58a6ff" : "#8b949e", marginRight: 8 }} />+ {isLayoutRunning ? "Pause Layout" : "Run Layout"}+ </button>+ <button onClick={reload} style={btnStyle("rgba(255,255,255,0.05)", "#e6edf3")} disabled={isLoading}>+ ↺ Reload+ </button>+ </div>+ </header>- {/* Right Side Panel */}- <NodePanel nodeId={selectedNodeId} />- </main>+ <div+ className="glass-hud hud-scrollbar"+ style={{+ pointerEvents: "auto",+ position: "absolute",+ right: 0,+ top: 60,+ bottom: 0,+ width: 360,+ overflowY: "auto",+ transition: "transform 0.3s cubic-bezier(0.16, 1, 0.3, 1)",+ transform: selectedNodeId ? "translateX(0)" : "translateX(100%)"+ }}+ >+ <NodePanel nodeId={selectedNodeId} />+ </div>++ </div></div>);}-// ─── Inline Styles ──────────────────────────────────────────────────────────-const rootStyle: React.CSSProperties = { display: "flex", flexDirection: "column", width: "100%", height: "100%", background: "#0d1117", overflow: "hidden" };-const headerStyle: React.CSSProperties = { display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 16px", background: "#161b22", borderBottom: "1px solid #30363d", flexShrink: 0 };-const mainStyle: React.CSSProperties = { display: "flex", flex: 1, overflow: "hidden" };-const panelStyle: React.CSSProperties = { width: 320, flexShrink: 0, background: "#161b22", borderLeft: "1px solid #30363d", padding: 16, overflowY: "auto" };-const btnStyle = (bg: string, color: string): React.CSSProperties => ({ background: bg, color, border: "1px solid #30363d", borderRadius: 6, padding: "6px 14px", cursor: "pointer", fontSize: 13, transition: "all 0.15s", fontWeight: 500 });\ No newline at end of file+const btnStyle = (bg: string, color: string): React.CSSProperties => ({+ background: bg,+ color,+ border: "1px solid rgba(255,255,255,0.1)",+ borderRadius: 4,+ padding: "8px 16px",+ cursor: "pointer",+ fontSize: 13,+ fontWeight: 500,+ transition: "all 0.2s",+ backdropFilter: "blur(4px)"+});\ No newline at end of filediff --git a/semantica-explorer/src/workspaces/GraphWorkspace/useLoadGraph.ts b/semantica-explorer/src/workspaces/GraphWorkspace/useLoadGraph.tsindex 3f3be2bc..4e6215fc 100644--- a/semantica-explorer/src/workspaces/GraphWorkspace/useLoadGraph.ts+++ b/semantica-explorer/src/workspaces/GraphWorkspace/useLoadGraph.ts@@ -1,8 +1,31 @@import { useQuery, useQueryClient } from "@tanstack/react-query";-// ADDED 'graph' to the import below so we can check node existenceimport { batchMergeEdges, batchMergeNodes, clearGraph, graph } from "../../store/graphStore";import type { EdgeAttributes, NodeAttributes } from "../../store/graphStore";+// colors and hasher+const CYBER_PALETTE = [+ "#58a6ff",+ "#3fb950",+ "#d2a8ff",+ "#f0883e",+ "#ff7b72",+ "#79c0ff",+ "#d29922",+ "#bc8cff",+ "#56d364",+ "#f778ba"+];+++const hashCategory = (str: string): number => {+ let hash = 0;+ for (let i = 0; i < str.length; i++) {+ hash = (hash << 5) - hash + str.charCodeAt(i);+ hash |= 0;+ }+ return Math.abs(hash);+};+interface ApiNode {id: string;type: string;@@ -71,8 +94,6 @@ async function fetchAllNodes(signal: AbortSignal): Promise<number> {const nodesToMerge = data.nodes.map((n) => {const x = n.properties?.x ?? (Math.random() * 1000 - 500);const y = n.properties?.y ?? (Math.random() * 1000 - 500);- const size = n.properties?.size ?? 5;- const color = n.properties?.color ?? "#6c8ebf";return {id: n.id,@@ -80,8 +101,6 @@ async function fetchAllNodes(signal: AbortSignal): Promise<number> {label: n.content || n.id,x,y,- size,- color,nodeType: n.type,content: n.content,valid_from: n.valid_from,@@ -136,7 +155,6 @@ async function fetchAllEdges(signal: AbortSignal): Promise<number> {return graph.hasNode(e.source) && graph.hasNode(e.target);});- // FIXED: Map over `validEdges` instead of `data.edges`const edgesToMerge = validEdges.map((e) => ({source: e.source,target: e.target,@@ -192,6 +210,33 @@ export function useLoadGraph(options: UseLoadGraphOptions = {}) {const nodeCount = await fetchAllNodes(signal);const edgeCount = await fetchAllEdges(signal);+ // Sizing and color mapper+ const maxDegree = graph.nodes().reduce((max, node) => Math.max(max, graph.degree(node)), 1);++ graph.updateEachNodeAttributes((node, attr) => {+ const categoryStr = String(attr.nodeType || attr.properties?.community || attr.properties?.category || "default");+ const colorIndex = hashCategory(categoryStr) % CYBER_PALETTE.length;+++ const degree = graph.degree(node);+ const minSize = 2;+ const maxSize = 25;++ // Flatten the power low curve to prevent giant graphs+ // from consuming the screen++ const sizeRatio = Math.log(degree + 1) / Math.log(maxDegree + 1);+ const dynamicSize = minSize + (maxSize - minSize) * sizeRatio;++ return {+ ...attr,+ color: CYBER_PALETTE[colorIndex],+ size: dynamicSize,+ borderColor: "#0d1117",+ borderSize: 0.5,+ };+ });+const summary: GraphLoadSummary = {nodeCount,edgeCount,