Add Cortex Portal — web visualization for knowledge graph

Express API server wrapping existing store/graph core with REST endpoints
for nodes, edges, graph, and search. React + Vite portal with React Flow
for interactive graph visualization, Tailwind CSS styling, and full CRUD UI
(sidebar, node panel, add/link modals, search bar, toast notifications).
This commit is contained in:
2026-02-02 17:01:29 +01:00
parent 21107443a7
commit 08c26754a8
25 changed files with 4566 additions and 1 deletions

View File

@@ -0,0 +1,84 @@
import { useState } from 'react';
import { api } from '../api';
import type { NodeKind } from '../types';
const KINDS: NodeKind[] = ['memory', 'component', 'task', 'decision'];
export default function AddNodeModal({
onClose,
onCreated,
}: {
onClose: () => void;
onCreated: () => void;
}) {
const [kind, setKind] = useState<NodeKind>('task');
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [status, setStatus] = useState('');
const [tags, setTags] = useState('');
const [loading, setLoading] = useState(false);
const submit = async () => {
if (!title.trim()) return;
setLoading(true);
try {
await api.addNode({
kind,
title,
content: content || undefined,
status: status || undefined,
tags: tags ? tags.split(',').map(t => t.trim()) : undefined,
});
onCreated();
onClose();
} finally {
setLoading(false);
}
};
return (
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50" onClick={onClose}>
<div className="bg-gray-900 border border-gray-700 rounded-lg p-6 w-96" onClick={e => e.stopPropagation()}>
<h2 className="text-lg font-semibold text-white mb-4">Add Node</h2>
<div className="space-y-3">
<div>
<label className="text-xs text-gray-400">Kind</label>
<div className="flex gap-2 mt-1">
{KINDS.map(k => (
<button
key={k}
onClick={() => setKind(k)}
className={`px-3 py-1 text-xs rounded ${kind === k ? 'bg-indigo-600 text-white' : 'bg-gray-800 text-gray-400'}`}
>
{k}
</button>
))}
</div>
</div>
<div>
<label className="text-xs text-gray-400">Title</label>
<input value={title} onChange={e => setTitle(e.target.value)} className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-sm text-white mt-1" />
</div>
<div>
<label className="text-xs text-gray-400">Content</label>
<textarea value={content} onChange={e => setContent(e.target.value)} rows={3} className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-sm text-white mt-1 resize-none" />
</div>
<div>
<label className="text-xs text-gray-400">Status</label>
<input value={status} onChange={e => setStatus(e.target.value)} className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-sm text-white mt-1" placeholder="e.g. todo, in-progress, done" />
</div>
<div>
<label className="text-xs text-gray-400">Tags (comma-separated)</label>
<input value={tags} onChange={e => setTags(e.target.value)} className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-sm text-white mt-1" />
</div>
</div>
<div className="flex gap-2 mt-5">
<button onClick={onClose} className="flex-1 py-2 bg-gray-800 text-gray-400 rounded text-sm">Cancel</button>
<button onClick={submit} disabled={loading || !title.trim()} className="flex-1 py-2 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white rounded text-sm font-medium">
{loading ? 'Creating...' : 'Create'}
</button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,107 @@
import { useMemo, useCallback } from 'react';
import {
ReactFlow,
MiniMap,
Controls,
Background,
useNodesState,
useEdgesState,
type Node as FlowNode,
type Edge as FlowEdge,
} from '@xyflow/react';
import { useGraph } from '../hooks/useGraph';
import type { CortexNode } from '../types';
const KIND_COLORS: Record<string, string> = {
memory: '#6366f1',
component: '#22c55e',
task: '#f59e0b',
decision: '#ef4444',
};
function layoutNodes(nodes: CortexNode[]): FlowNode[] {
const cols = Math.max(Math.ceil(Math.sqrt(nodes.length)), 1);
return nodes.map((n, i) => ({
id: n.id,
position: { x: (i % cols) * 280 + 50, y: Math.floor(i / cols) * 140 + 50 },
data: { label: n.title, kind: n.kind, status: n.status },
style: {
background: KIND_COLORS[n.kind] || '#6b7280',
color: '#fff',
border: 'none',
borderRadius: 8,
padding: '12px 16px',
fontSize: 13,
fontWeight: 500,
minWidth: 160,
},
}));
}
export default function GraphView({
selectedId,
onSelect,
}: {
selectedId: string | null;
onSelect: (id: string) => void;
}) {
const { data, isLoading } = useGraph();
const initialNodes = useMemo(() => (data ? layoutNodes(data.nodes) : []), [data]);
const initialEdges = useMemo<FlowEdge[]>(
() =>
data
? data.edges.map((e) => ({
id: e.id,
source: e.fromId,
target: e.toId,
label: e.type,
animated: e.type === 'blocked_by',
style: { stroke: '#64748b' },
labelStyle: { fill: '#94a3b8', fontSize: 11 },
}))
: [],
[data],
);
const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
// Sync when data changes
useMemo(() => {
setNodes(initialNodes);
setEdges(initialEdges);
}, [initialNodes, initialEdges, setNodes, setEdges]);
const onNodeClick = useCallback(
(_: any, node: FlowNode) => onSelect(node.id),
[onSelect],
);
if (isLoading) {
return (
<div className="flex items-center justify-center h-full text-gray-400">
Loading graph...
</div>
);
}
return (
<ReactFlow
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onNodeClick={onNodeClick}
fitView
className="bg-gray-950"
>
<Background color="#334155" gap={20} />
<Controls className="!bg-gray-800 !border-gray-700 [&>button]:!bg-gray-800 [&>button]:!border-gray-700 [&>button]:!text-gray-300" />
<MiniMap
nodeColor={(n) => KIND_COLORS[(n.data as any)?.kind] || '#6b7280'}
className="!bg-gray-900 !border-gray-700"
/>
</ReactFlow>
);
}

View File

@@ -0,0 +1,77 @@
import { useState } from 'react';
import { api } from '../api';
import { useNodes } from '../hooks/useNodes';
import type { EdgeType } from '../types';
const EDGE_TYPES: EdgeType[] = [
'depends_on', 'contains', 'implements', 'blocked_by',
'subtask_of', 'relates_to', 'supersedes', 'about',
];
export default function LinkModal({
fromId,
onClose,
onCreated,
}: {
fromId: string;
onClose: () => void;
onCreated: () => void;
}) {
const { data: nodes } = useNodes();
const [toId, setToId] = useState('');
const [type, setType] = useState<EdgeType>('relates_to');
const [loading, setLoading] = useState(false);
const submit = async () => {
if (!toId) return;
setLoading(true);
try {
await api.addEdge({ fromId, toId, type });
onCreated();
onClose();
} finally {
setLoading(false);
}
};
const targets = nodes?.filter(n => n.id !== fromId) || [];
return (
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50" onClick={onClose}>
<div className="bg-gray-900 border border-gray-700 rounded-lg p-6 w-96" onClick={e => e.stopPropagation()}>
<h2 className="text-lg font-semibold text-white mb-4">Create Link</h2>
<div className="space-y-3">
<div>
<label className="text-xs text-gray-400">Edge Type</label>
<select
value={type}
onChange={e => setType(e.target.value as EdgeType)}
className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-sm text-white mt-1"
>
{EDGE_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
</select>
</div>
<div>
<label className="text-xs text-gray-400">Target Node</label>
<select
value={toId}
onChange={e => setToId(e.target.value)}
className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-sm text-white mt-1"
>
<option value="">Select a node...</option>
{targets.map(n => (
<option key={n.id} value={n.id}>[{n.kind}] {n.title}</option>
))}
</select>
</div>
</div>
<div className="flex gap-2 mt-5">
<button onClick={onClose} className="flex-1 py-2 bg-gray-800 text-gray-400 rounded text-sm">Cancel</button>
<button onClick={submit} disabled={loading || !toId} className="flex-1 py-2 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white rounded text-sm font-medium">
{loading ? 'Linking...' : 'Create Link'}
</button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,135 @@
import { useState, useEffect } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '../api';
import type { NodeWithConnections } from '../types';
export default function NodePanel({
nodeId,
onClose,
onLink,
onRefresh,
onNotify,
}: {
nodeId: string;
onClose: () => void;
onLink: (id: string) => void;
onRefresh: () => void;
onNotify: (msg: string) => void;
}) {
const qc = useQueryClient();
const { data: node, isLoading } = useQuery({
queryKey: ['node', nodeId],
queryFn: () => api.getNode(nodeId),
});
const [editing, setEditing] = useState<string | null>(null);
const [editValue, setEditValue] = useState('');
useEffect(() => {
const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
}, [onClose]);
if (isLoading || !node) {
return (
<div className="w-80 bg-gray-900 border-l border-gray-800 p-4 text-gray-400">
Loading...
</div>
);
}
const save = async (field: string, value: string) => {
const body: any = {};
if (field === 'tags') body.tags = value.split(',').map(t => t.trim()).filter(Boolean);
else body[field] = value;
await api.updateNode(nodeId, body);
qc.invalidateQueries({ queryKey: ['node', nodeId] });
onRefresh();
setEditing(null);
onNotify(`Updated ${field}`);
};
const handleDelete = async () => {
if (!confirm('Delete this node?')) return;
await api.deleteNode(nodeId, true);
onRefresh();
onClose();
onNotify('Node deleted');
};
const Field = ({ label, field, value }: { label: string; field: string; value: string }) => (
<div className="mb-3">
<label className="text-[10px] uppercase tracking-wide text-gray-500">{label}</label>
{editing === field ? (
<div className="flex gap-1 mt-1">
<input
value={editValue}
onChange={(e) => setEditValue(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && save(field, editValue)}
className="flex-1 bg-gray-800 border border-gray-600 rounded px-2 py-1 text-sm text-white"
autoFocus
/>
<button onClick={() => save(field, editValue)} className="text-xs text-indigo-400">Save</button>
<button onClick={() => setEditing(null)} className="text-xs text-gray-500">Cancel</button>
</div>
) : (
<div
onClick={() => { setEditing(field); setEditValue(value); }}
className="text-sm text-gray-300 mt-0.5 cursor-pointer hover:text-white min-h-[20px]"
>
{value || <span className="text-gray-600 italic">empty</span>}
</div>
)}
</div>
);
return (
<aside className="w-80 bg-gray-900 border-l border-gray-800 flex flex-col h-full overflow-y-auto">
<div className="p-4 border-b border-gray-800 flex justify-between items-start">
<div>
<span className="text-[10px] uppercase tracking-wide text-gray-500">{node.kind}</span>
<h2 className="text-base font-semibold text-white">{node.title}</h2>
<span className="text-[10px] text-gray-600">{node.id.slice(0, 8)}</span>
</div>
<button onClick={onClose} className="text-gray-500 hover:text-white text-lg">&times;</button>
</div>
<div className="p-4 flex-1">
<Field label="Status" field="status" value={node.status || ''} />
<Field label="Content" field="content" value={node.content} />
<Field label="Tags" field="tags" value={node.tags.join(', ')} />
<div className="mt-4">
<label className="text-[10px] uppercase tracking-wide text-gray-500">Connections</label>
{node.connections.outgoing.length === 0 && node.connections.incoming.length === 0 && (
<p className="text-sm text-gray-600 mt-1">No connections</p>
)}
{node.connections.outgoing.map((c) => (
<div key={c.id} className="text-sm text-gray-400 mt-1">
<span className="text-gray-500">&rarr; {c.type}</span> {c.node.title}
</div>
))}
{node.connections.incoming.map((c) => (
<div key={c.id} className="text-sm text-gray-400 mt-1">
<span className="text-gray-500">&larr; {c.type}</span> {c.node.title}
</div>
))}
</div>
</div>
<div className="p-4 border-t border-gray-800 flex gap-2">
<button
onClick={() => onLink(nodeId)}
className="flex-1 py-1.5 bg-gray-800 hover:bg-gray-700 text-gray-300 rounded text-sm"
>
Link to...
</button>
<button
onClick={handleDelete}
className="flex-1 py-1.5 bg-red-900/50 hover:bg-red-800 text-red-300 rounded text-sm"
>
Delete
</button>
</div>
</aside>
);
}

View File

@@ -0,0 +1,51 @@
import { useState } from 'react';
import { api } from '../api';
import type { SearchResult } from '../types';
export default function SearchBar({ onSelect }: { onSelect: (id: string) => void }) {
const [query, setQuery] = useState('');
const [results, setResults] = useState<SearchResult[]>([]);
const [open, setOpen] = useState(false);
const search = async () => {
if (!query.trim()) return;
const res = await api.search(query);
setResults(res);
setOpen(true);
};
return (
<div className="relative">
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && search()}
placeholder="Search nodes..."
className="w-full bg-gray-800 border border-gray-700 rounded px-3 py-1.5 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-indigo-500"
/>
{open && results.length > 0 && (
<div className="absolute top-full left-0 right-0 mt-1 bg-gray-800 border border-gray-700 rounded shadow-lg z-50 max-h-60 overflow-y-auto">
{results.map((r) => (
<button
key={r.node.id}
onClick={() => { onSelect(r.node.id); setOpen(false); setQuery(''); }}
className="w-full text-left p-2 hover:bg-gray-700 text-sm text-gray-300 border-b border-gray-700 last:border-0"
>
<span className="text-[10px] text-gray-500 uppercase">{r.node.kind}</span>
<div className="truncate">{r.node.title}</div>
<span className="text-[10px] text-gray-500">score: {r.score.toFixed(2)}</span>
</button>
))}
</div>
)}
{open && results.length === 0 && (
<div className="absolute top-full left-0 right-0 mt-1 bg-gray-800 border border-gray-700 rounded p-2 text-sm text-gray-500 z-50">
No results
</div>
)}
{open && (
<div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
)}
</div>
);
}

View File

@@ -0,0 +1,69 @@
import { useState } from 'react';
import { useNodes } from '../hooks/useNodes';
import SearchBar from './SearchBar';
import type { NodeKind } from '../types';
const KINDS: (NodeKind | '')[] = ['', 'memory', 'component', 'task', 'decision'];
export default function Sidebar({
selectedId,
onSelect,
onAddNode,
}: {
selectedId: string | null;
onSelect: (id: string) => void;
onAddNode: () => void;
}) {
const [kindFilter, setKindFilter] = useState('');
const { data: nodes, isLoading } = useNodes(kindFilter ? { kind: kindFilter } : undefined);
return (
<aside className="w-72 bg-gray-900 border-r border-gray-800 flex flex-col h-full">
<div className="p-4 border-b border-gray-800">
<h1 className="text-lg font-bold text-white mb-3">Cortex Portal</h1>
<SearchBar onSelect={onSelect} />
<div className="flex gap-1 mt-3 flex-wrap">
{KINDS.map((k) => (
<button
key={k}
onClick={() => setKindFilter(k)}
className={`px-2 py-0.5 text-xs rounded ${
kindFilter === k
? 'bg-indigo-600 text-white'
: 'bg-gray-800 text-gray-400 hover:bg-gray-700'
}`}
>
{k || 'All'}
</button>
))}
</div>
</div>
<div className="flex-1 overflow-y-auto p-2">
{isLoading && <p className="text-gray-500 text-sm p-2">Loading...</p>}
{nodes?.map((n) => (
<button
key={n.id}
onClick={() => onSelect(n.id)}
className={`w-full text-left p-2 rounded mb-1 text-sm ${
selectedId === n.id
? 'bg-indigo-600/30 text-white'
: 'hover:bg-gray-800 text-gray-300'
}`}
>
<span className="text-[10px] uppercase tracking-wide text-gray-500">{n.kind}</span>
<div className="truncate">{n.title}</div>
{n.status && <span className="text-[10px] text-gray-500">{n.status}</span>}
</button>
))}
</div>
<div className="p-3 border-t border-gray-800">
<button
onClick={onAddNode}
className="w-full py-2 bg-indigo-600 hover:bg-indigo-500 text-white rounded text-sm font-medium"
>
+ Add Node
</button>
</div>
</aside>
);
}

View File

@@ -0,0 +1,7 @@
export default function Toast({ message }: { message: string }) {
return (
<div className="fixed bottom-6 right-6 bg-green-600 text-white px-4 py-2 rounded-lg shadow-lg z-50 animate-fade-in">
{message}
</div>
);
}