Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat(ui): complete phase 2 massive graph rendering and api alignment

ZohaibHassan169203c2d68404
diff --git a/semantica-explorer/package-lock.json b/semantica-explorer/package-lock.json
index f5d97d3f..1a2b195e 100644
--- a/semantica-explorer/package-lock.json
+++ b/semantica-explorer/package-lock.json
@@ -9,11 +9,14 @@
"version": "0.0.0",
"dependencies": {
"@tanstack/react-query": "^5.95.2",
+ "graphology": "^0.26.0",
+ "graphology-layout-forceatlas2": "^0.10.1",
"lucide-react": "^1.7.0",
"react": "^19.2.4",
"react-arborist": "^3.4.3",
"react-dom": "^19.2.4",
- "react-dropzone": "^15.0.0"
+ "react-dropzone": "^15.0.0",
+ "sigma": "^3.0.2"
},
"devDependencies": {
"@babel/core": "^7.29.0",
@@ -1869,6 +1872,15 @@
"node": ">=0.10.0"
}
},
+ "node_modules/events": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
+ "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.8.x"
+ }
+ },
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@@ -2021,6 +2033,46 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/graphology": {
+ "version": "0.26.0",
+ "resolved": "https://registry.npmjs.org/graphology/-/graphology-0.26.0.tgz",
+ "integrity": "sha512-8SSImzgUUYC89Z042s+0r/vMibY7GX/Emz4LDO5e7jYXhuoWfHISPFJYjpRLUSJGq6UQ6xlenvX1p/hJdfXuXg==",
+ "license": "MIT",
+ "dependencies": {
+ "events": "^3.3.0"
+ },
+ "peerDependencies": {
+ "graphology-types": ">=0.24.0"
+ }
+ },
+ "node_modules/graphology-layout-forceatlas2": {
+ "version": "0.10.1",
+ "resolved": "https://registry.npmjs.org/graphology-layout-forceatlas2/-/graphology-layout-forceatlas2-0.10.1.tgz",
+ "integrity": "sha512-ogzBeF1FvWzjkikrIFwxhlZXvD2+wlY54lqhsrWprcdPjopM2J9HoMweUmIgwaTvY4bUYVimpSsOdvDv1gPRFQ==",
+ "license": "MIT",
+ "dependencies": {
+ "graphology-utils": "^2.1.0"
+ },
+ "peerDependencies": {
+ "graphology-types": ">=0.19.0"
+ }
+ },
+ "node_modules/graphology-types": {
+ "version": "0.24.8",
+ "resolved": "https://registry.npmjs.org/graphology-types/-/graphology-types-0.24.8.tgz",
+ "integrity": "sha512-hDRKYXa8TsoZHjgEaysSRyPdT6uB78Ci8WnjgbStlQysz7xR52PInxNsmnB7IBOM1BhikxkNyCVEFgmPKnpx3Q==",
+ "license": "MIT",
+ "peer": true
+ },
+ "node_modules/graphology-utils": {
+ "version": "2.5.2",
+ "resolved": "https://registry.npmjs.org/graphology-utils/-/graphology-utils-2.5.2.tgz",
+ "integrity": "sha512-ckHg8MXrXJkOARk56ZaSCM1g1Wihe2d6iTmz1enGOz4W/l831MBCKSayeFQfowgF8wd+PQ4rlch/56Vs/VZLDQ==",
+ "license": "MIT",
+ "peerDependencies": {
+ "graphology-types": ">=0.23.0"
+ }
+ },
"node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
@@ -2976,6 +3028,16 @@
"node": ">=8"
}
},
+ "node_modules/sigma": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/sigma/-/sigma-3.0.2.tgz",
+ "integrity": "sha512-/BUbeOwPGruiBOm0YQQ6ZMcLIZ6tf/W+Jcm7dxZyAX0tK3WP9/sq7/NAWBxPIxVahdGjCJoGwej0Gdrv0DxlQQ==",
+ "license": "MIT",
+ "dependencies": {
+ "events": "^3.3.0",
+ "graphology-utils": "^2.5.2"
+ }
+ },
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
diff --git a/semantica-explorer/package.json b/semantica-explorer/package.json
index 569d2f90..ae5688e1 100644
--- a/semantica-explorer/package.json
+++ b/semantica-explorer/package.json
@@ -11,11 +11,14 @@
},
"dependencies": {
"@tanstack/react-query": "^5.95.2",
+ "graphology": "^0.26.0",
+ "graphology-layout-forceatlas2": "^0.10.1",
"lucide-react": "^1.7.0",
"react": "^19.2.4",
"react-arborist": "^3.4.3",
"react-dom": "^19.2.4",
- "react-dropzone": "^15.0.0"
+ "react-dropzone": "^15.0.0",
+ "sigma": "^3.0.2"
},
"devDependencies": {
"@babel/core": "^7.29.0",
diff --git a/semantica-explorer/src/App.tsx b/semantica-explorer/src/App.tsx
index fd6d972a..d7675b56 100644
--- a/semantica-explorer/src/App.tsx
+++ b/semantica-explorer/src/App.tsx
@@ -1,17 +1,71 @@
+/**
+ * src/App.tsx
+ */
+import { useState } from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { VocabularyWorkspace } from './workspaces/VocabularyWorkspace/VocabularyWorkspace';
-
+import { GraphWorkspace } from './workspaces/GraphWorkspace/GraphWorkspace';
const queryClient = new QueryClient();
-function App() {
+export default function App() {
+ const [activeWorkspace, setActiveWorkspace] = useState<'vocabulary' | 'graph'>('graph');
+
return (
<QueryClientProvider client={queryClient}>
- <div style={{ margin: 0, padding: 0, width: '100vw', height: '100vh' }}>
- <VocabularyWorkspace />
+ <div style={{ display: 'flex', width: '100vw', height: '100vh', margin: 0, padding: 0, backgroundColor: '#0d1117', fontFamily: "system-ui, -apple-system, sans-serif" }}>
+
+
+ <nav style={{
+ width: '64px',
+ backgroundColor: '#010409',
+ borderRight: '1px solid #30363d',
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ paddingTop: '16px',
+ gap: '16px'
+ }}>
+ {/* Logo / Brand */}
+ <div style={{ width: '32px', height: '32px', backgroundColor: '#238636', borderRadius: '8px', marginBottom: '24px' }} title="Semantica" />
+
+ {/* Graph Icon Button */}
+ <button
+ onClick={() => setActiveWorkspace('graph')}
+ title="Graph Explorer"
+ style={{
+ width: '40px', height: '40px', borderRadius: '8px', cursor: 'pointer',
+ border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center',
+ backgroundColor: activeWorkspace === 'graph' ? '#1f6feb' : 'transparent',
+ color: activeWorkspace === 'graph' ? '#fff' : '#8b949e',
+ transition: 'all 0.2s'
+ }}
+ >
+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="18" cy="5" r="3"></circle><circle cx="6" cy="12" r="3"></circle><circle cx="18" cy="19" r="3"></circle><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"></line><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"></line></svg>
+ </button>
+
+ {/* Vocabulary Icon Button */}
+ <button
+ onClick={() => setActiveWorkspace('vocabulary')}
+ title="Vocabulary & Ontology"
+ style={{
+ width: '40px', height: '40px', borderRadius: '8px', cursor: 'pointer',
+ border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center',
+ backgroundColor: activeWorkspace === 'vocabulary' ? '#1f6feb' : 'transparent',
+ color: activeWorkspace === 'vocabulary' ? '#fff' : '#8b949e',
+ transition: 'all 0.2s'
+ }}
+ >
+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20"></path></svg>
+ </button>
+ </nav>
+
+ {/* ── Active Workspace Area ────────────────────────────────────── */}
+ <div style={{ flex: 1, position: 'relative', overflow: 'hidden' }}>
+ {activeWorkspace === 'graph' && <GraphWorkspace />}
+ {activeWorkspace === 'vocabulary' && <VocabularyWorkspace />}
+ </div>
</div>
</QueryClientProvider>
);
-}
-
-export default App;
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/semantica-explorer/src/store/graphStore.ts b/semantica-explorer/src/store/graphStore.ts
new file mode 100644
index 00000000..77e796ee
--- /dev/null
+++ b/semantica-explorer/src/store/graphStore.ts
@@ -0,0 +1,62 @@
+import Graph from "graphology";
+
+
+export const graph = new Graph({
+ type: "directed",
+ multi: false,
+ allowSelfLoops: false
+});
+
+
+
+export interface NodeAttributes {
+
+ label: string;
+ x: number;
+ y: number;
+ size: number;
+ color: string;
+ highlighted?: boolean;
+
+ nodeType: string;
+ content: string;
+ valid_from?: string | null;
+ valid_until?: string | null;
+ properties: Record<string, any>;
+}
+
+export interface EdgeAttributes {
+
+ size?: number;
+ color?: string;
+
+
+ edgeType: string;
+ weight: number;
+ properties: Record<string, any>;
+}
+
+
+export function batchMergeNodes(
+ nodes: { id: string; attributes: NodeAttributes }[]
+): void {
+ for (const { id, attributes } of nodes) {
+ graph.mergeNode(id, attributes);
+ }
+}
+
+
+export function batchMergeEdges(
+ edges: { source: string; target: string; attributes: EdgeAttributes }[]
+): void {
+ for (const { source, target, attributes } of edges) {
+
+ if (graph.hasNode(source) && graph.hasNode(target)) {
+ graph.mergeDirectedEdge(source, target, attributes);
+ }
+ }
+}
+
+export function clearGraph(): void {
+ graph.clear();
+}
\ No newline at end of file
diff --git a/semantica-explorer/src/workspaces/GraphWorkspace/GraphCanvas.tsx b/semantica-explorer/src/workspaces/GraphWorkspace/GraphCanvas.tsx
new file mode 100644
index 00000000..c2618c89
--- /dev/null
+++ b/semantica-explorer/src/workspaces/GraphWorkspace/GraphCanvas.tsx
@@ -0,0 +1,109 @@
+/**
+ * src/workspaces/GraphWorkspace/GraphCanvas.tsx
+ */
+import { useEffect, useRef, 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;
+ isLayoutRunning: boolean;
+ className?: string;
+}
+
+const FA2_SETTINGS = {
+ iterations: 50,
+ settings: {
+ barnesHutOptimize: true,
+ barnesHutTheta: 0.5,
+ adjustSizes: false,
+ gravity: 1,
+ slowDown: 10,
+ },
+};
+
+const SIGMA_SETTINGS = {
+ allowInvalidContainer: true,
+ labelRenderedSizeThreshold: 6,
+ defaultNodeType: "circle",
+ defaultEdgeType: "arrow",
+ hideEdgesOnMove: true,
+ webGLTarget: "webgl2" as const,
+};
+
+export function GraphCanvas({ onNodeClick, isLayoutRunning, className }: GraphCanvasProps) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const sigmaRef = useRef<Sigma | null>(null);
+ const fa2Ref = useRef<FA2Layout | null>(null);
+
+ useEffect(() => {
+ if (!containerRef.current || sigmaRef.current) return;
+
+ const sigma = new Sigma(graph, containerRef.current, SIGMA_SETTINGS);
+ sigmaRef.current = sigma;
+
+ const resizeObserver = new ResizeObserver(() => {
+ if (containerRef.current && containerRef.current.offsetWidth > 0) {
+ sigma.refresh();
+ }
+ });
+ resizeObserver.observe(containerRef.current);
+
+
+ sigma.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));
+ });
+
+ return () => {
+ resizeObserver.disconnect();
+ sigma.kill();
+ sigmaRef.current = null;
+ };
+ }, [onNodeClick]);
+
+ useEffect(() => {
+ if (isLayoutRunning) {
+ if (!fa2Ref.current) {
+ fa2Ref.current = new FA2Layout(graph, FA2_SETTINGS);
+ }
+ fa2Ref.current.start();
+ } else {
+ fa2Ref.current?.stop();
+ }
+
+ return () => {
+ fa2Ref.current?.kill();
+ fa2Ref.current = null;
+ };
+ }, [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" }} />
+ <button
+ onClick={handleFitView}
+ style={{
+ position: "absolute", bottom: 16, right: 16, padding: "8px 16px",
+ background: "#1f6feb", color: "#fff", border: "none", borderRadius: 6,
+ cursor: "pointer", fontWeight: 600, zIndex: 10,
+ }}
+ >
+ Fit View
+ </button>
+ </div>
+ );
+}
\ No newline at end of file
diff --git a/semantica-explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx b/semantica-explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx
new file mode 100644
index 00000000..1a774caa
--- /dev/null
+++ b/semantica-explorer/src/workspaces/GraphWorkspace/GraphWorkspace.tsx
@@ -0,0 +1,138 @@
+/**
+ * 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 ────────────────────────────────────────────
+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.
+ </p>
+ </aside>
+ );
+ }
+
+ // 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>
+ </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>
+ </aside>
+ );
+}
+
+// ─── Main Workspace Component ──────────────────────────────────────────────
+export function GraphWorkspace() {
+ // THE ONLY REACT STATE FOR THE GRAPH
+ const [selectedNodeId, setSelectedNodeId] = useState<string>("");
+ const [isLayoutRunning, setIsLayoutRunning] = useState(false);
+
+ const reload = useReloadGraph();
+
+ // Stable callback to prevent unnecessary re-renders
+ const handleNodeClick = useCallback((nodeId: string) => {
+ setSelectedNodeId(nodeId);
+ }, []);
+
+ // Fetch data into the mutable singleton
+ const { data: summary, isLoading, isError, error } = useLoadGraph({
+ enabled: true,
+ onGraphReady: () => {
+ // Auto-start the ForceAtlas2 layout once data finishes downloading
+ setIsLayoutRunning(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>
+
+ {/* Right Side Panel */}
+ <NodePanel nodeId={selectedNodeId} />
+ </main>
+ </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
diff --git a/semantica-explorer/src/workspaces/GraphWorkspace/useLoadGraph.ts b/semantica-explorer/src/workspaces/GraphWorkspace/useLoadGraph.ts
new file mode 100644
index 00000000..3f3be2bc
--- /dev/null
+++ b/semantica-explorer/src/workspaces/GraphWorkspace/useLoadGraph.ts
@@ -0,0 +1,211 @@
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+// ADDED 'graph' to the import below so we can check node existence
+import { batchMergeEdges, batchMergeNodes, clearGraph, graph } from "../../store/graphStore";
+import type { EdgeAttributes, NodeAttributes } from "../../store/graphStore";
+
+interface ApiNode {
+ id: string;
+ type: string;
+ content: string;
+ properties: Record<string, any>;
+ valid_from?: string | null;
+ valid_until?: string | null;
+}
+
+interface ApiEdge {
+ source: string;
+ target: string;
+ type: string;
+ weight: number;
+ properties: Record<string, any>;
+}
+
+interface NodeListResponse {
+ nodes: ApiNode[];
+ total: number;
+ skip: number;
+ limit: number;
+}
+
+interface EdgeListResponse {
+ edges: ApiEdge[];
+ total: number;
+ skip: number;
+ limit: number;
+}
+
+export interface GraphLoadSummary {
+ nodeCount: number;
+ edgeCount: number;
+ loadTimeMs: number;
+}
+
+const PAGE_LIMIT = 1000;
+
+async function fetchAllNodes(signal: AbortSignal): Promise<number> {
+ let skip = 0;
+ let totalMerged = 0;
+ let hasMore = true;
+
+ while (hasMore) {
+ const url = new URL("/api/graph/nodes", window.location.origin);
+ url.searchParams.set("limit", String(PAGE_LIMIT));
+ url.searchParams.set("skip", String(skip));
+
+ const res = await fetch(url.toString(), { signal });
+ if (!res.ok) {
+ const errorBody = await res.text();
+ if (res.status === 422) {
+ console.error(`🚨 FastAPI 422 Crash Report at skip=${skip}:`, errorBody);
+ break;
+ }
+ throw new Error(`Fetch failed: ${res.status}`);
+ }
+
+ const data: NodeListResponse = await res.json();
+
+ if (!data.nodes || data.nodes.length === 0) {
+ break;
+ }
+
+ 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,
+ attributes: {
+ label: n.content || n.id,
+ x,
+ y,
+ size,
+ color,
+ nodeType: n.type,
+ content: n.content,
+ valid_from: n.valid_from,
+ valid_until: n.valid_until,
+ properties: n.properties,
+ } as NodeAttributes,
+ };
+ });
+
+ batchMergeNodes(nodesToMerge);
+ totalMerged += nodesToMerge.length;
+ skip += PAGE_LIMIT;
+
+ if (data.nodes.length < PAGE_LIMIT) {
+ hasMore = false;
+ }
+
+ await yieldToMain();
+ }
+
+ return totalMerged;
+}
+
+async function fetchAllEdges(signal: AbortSignal): Promise<number> {
+ let skip = 0;
+ let totalMerged = 0;
+ let hasMore = true;
+
+ while (hasMore) {
+ const url = new URL("/api/graph/edges", window.location.origin);
+ url.searchParams.set("limit", String(PAGE_LIMIT));
+ url.searchParams.set("skip", String(skip));
+
+ const res = await fetch(url.toString(), { signal });
+ if (!res.ok) {
+ const errorBody = await res.text();
+ if (res.status === 422) {
+ console.error(`🚨 FastAPI 422 Crash Report at skip=${skip}:`, errorBody);
+ break;
+ }
+ throw new Error(`Fetch failed: ${res.status}`);
+ }
+
+ const data: EdgeListResponse = await res.json();
+
+ if (!data.edges || data.edges.length === 0) {
+ break;
+ }
+
+ // Filter out edges pointing to missing nodes
+ const validEdges = data.edges.filter((e) => {
+ 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,
+ attributes: {
+ weight: e.weight,
+ edgeType: e.type,
+ properties: e.properties,
+ size: e.properties?.size ?? 1,
+ color: e.properties?.color ?? "#444C56",
+ } as EdgeAttributes,
+ }));
+
+ batchMergeEdges(edgesToMerge);
+ totalMerged += edgesToMerge.length;
+ skip += PAGE_LIMIT;
+
+ if (data.edges.length < PAGE_LIMIT) {
+ hasMore = false;
+ }
+
+ await yieldToMain();
+ }
+
+ return totalMerged;
+}
+
+function yieldToMain(): Promise<void> {
+ if ("scheduler" in window && typeof (window as any).scheduler.yield === "function") {
+ return (window as any).scheduler.yield();
+ }
+ return new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+interface UseLoadGraphOptions {
+ enabled?: boolean;
+ onGraphReady?: (summary: GraphLoadSummary) => void;
+}
+
+export function useLoadGraph(options: UseLoadGraphOptions = {}) {
+ const { enabled = true, onGraphReady } = options;
+ const queryClient = useQueryClient();
+
+ return useQuery<GraphLoadSummary>({
+ queryKey: ["graph", "full-load"],
+ enabled,
+ staleTime: Infinity,
+
+ queryFn: async ({ signal }): Promise<GraphLoadSummary> => {
+ const t0 = performance.now();
+
+ clearGraph();
+
+ const nodeCount = await fetchAllNodes(signal);
+ const edgeCount = await fetchAllEdges(signal);
+
+ const summary: GraphLoadSummary = {
+ nodeCount,
+ edgeCount,
+ loadTimeMs: Math.round(performance.now() - t0),
+ };
+
+ onGraphReady?.(summary);
+
+ return summary;
+ },
+ });
+}
+
+export function useReloadGraph() {
+ const queryClient = useQueryClient();
+ return () => queryClient.invalidateQueries({ queryKey: ["graph", "full-load"] });
+}
\ No newline at end of file
diff --git a/semantica/explorer/routes/graph.py b/semantica/explorer/routes/graph.py
index b0b8bd4c..84ce7523 100644
--- a/semantica/explorer/routes/graph.py
+++ b/semantica/explorer/routes/graph.py
@@ -44,7 +44,7 @@ async def list_nodes(
type: Optional[str] = Query(None, description="Filter by node type"),
search: Optional[str] = Query(None, description="Keyword search over node content"),
skip: int = Query(0, ge=0),
- limit: int = Query(100, ge=1, le=1000),
+ limit: int = Query(100, ge=1, le=5000),
session: GraphSession = Depends(get_session),
):
"""List nodes with optional filtering and pagination."""
diff --git a/semantica/explorer/routes/vocabulary.py b/semantica/explorer/routes/vocabulary.py
index 64b60622..d444b25c 100644
--- a/semantica/explorer/routes/vocabulary.py
+++ b/semantica/explorer/routes/vocabulary.py
@@ -114,11 +114,13 @@ async def get_hierarchy(
if src in node_map and tgt in node_map:
if etype == "skos:broader":
# Source is narrower (child), Target is broader (parent)
- parent_to_children[tgt].append(src)
+ if src not in parent_to_children[tgt]:
+ parent_to_children[tgt].append(src)
has_parent.add(src)
elif etype == "skos:narrower":
# Source is broader (parent), Target is narrower (child)
- parent_to_children[src].append(tgt)
+ if tgt not in parent_to_children[src]:
+ parent_to_children[src].append(tgt)
has_parent.add(tgt)
# Assemble nested tree — cycle-safe via visited set.