File size: 20,904 Bytes
584bf0d | 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 | import { useState, useRef, useEffect } from 'react'
import type { ChatMessage, Metrics, MemorySamples } from '../types'
import { SourceBadge } from './SourceBadge'
interface ApiProps {
connected: boolean
metrics: Metrics | null
loading: boolean
sendMessage: (message: string, temperature?: number, maxTokens?: number) => Promise<any>
teachModel: (question: string, answer: string) => Promise<any>
learnText: (text: string) => Promise<any>
dream: (cycles: number) => Promise<any>
reason: (question: string) => Promise<any>
}
type SidebarTab = 'chat' | 'teach' | 'learn' | 'dream' | 'stats'
const SUGGESTIONS = [
{ icon: '👋', title: 'Say hello', q: 'hello' },
{ icon: '🧠', title: 'Who are you?', q: 'who are you' },
{ icon: '🐍', title: 'What is Python?', q: 'what is python' },
{ icon: '✨', title: 'Write a poem', q: 'write a poem about the sea' },
{ icon: '💻', title: 'Write code', q: 'write a python function to check if a number is prime' },
{ icon: '📖', title: 'Explain something', q: 'explain how the internet works' },
{ icon: '🌑', title: 'Science facts', q: 'what is dark matter' },
{ icon: '💡', title: 'Get advice', q: 'how to stay focused' },
]
export function ChatGPTLayout({ api }: { api: ApiProps }) {
const [messages, setMessages] = useState<ChatMessage[]>([])
const [input, setInput] = useState('')
const [sidebarOpen, setSidebarOpen] = useState(true)
const [tab, setTab] = useState<SidebarTab>('chat')
const scrollRef = useRef<HTMLDivElement>(null)
// Teach state
const [teachQ, setTeachQ] = useState('')
const [teachA, setTeachA] = useState('')
const [teachHistory, setTeachHistory] = useState<{q: string, a: string, tokens: number}[]>([])
// Learn state
const [learnText, setLearnText] = useState('')
const [learnResult, setLearnResult] = useState<any>(null)
// Dream state
const [dreamResult, setDreamResult] = useState<any>(null)
useEffect(() => {
if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight
}, [messages, api.loading])
const handleSend = async () => {
const msg = input.trim()
if (!msg || api.loading) return
setInput('')
const userMsg: ChatMessage = { id: `u-${Date.now()}`, role: 'user', text: msg, timestamp: Date.now() }
setMessages(prev => [...prev, userMsg])
try {
const resp = await api.sendMessage(msg)
setMessages(prev => [...prev, {
id: `b-${Date.now()}`, role: 'palimpseste', text: resp.response,
confidence: resp.confidence, source: resp.source,
explanation: resp.explanation, chain: resp.chain,
elapsed_ms: resp.elapsed_ms, timestamp: Date.now(),
}])
} catch {
setMessages(prev => [...prev, {
id: `e-${Date.now()}`, role: 'palimpseste',
text: '⚠️ Cannot connect to server. Is the API running on :3332?',
source: 'fallback', confidence: 0, timestamp: Date.now(),
}])
}
}
const handleTeach = async () => {
if (!teachQ.trim() || !teachA.trim() || api.loading) return
try {
const resp = await api.teachModel(teachQ, teachA)
setTeachHistory(prev => [{ q: teachQ, a: teachA, tokens: resp.tokens_written }, ...prev])
setTeachQ(''); setTeachA('')
} catch {}
}
const handleLearn = async () => {
if (!learnText.trim() || api.loading) return
try {
const r = await api.learnText(learnText)
setLearnResult(r)
} catch {}
}
const handleDream = async () => {
try {
const r = await api.dream(3)
setDreamResult(r)
} catch {}
}
const newChat = () => { setMessages([]); setTab('chat') }
return (
<div className="h-screen w-screen flex bg-pal-bg relative overflow-hidden">
{/* Background orbs */}
<div className="bg-orbs">
<div className="bg-orb" style={{ width: '500px', height: '500px', background: '#7c3aed', top: '-100px', left: '-100px' }} />
<div className="bg-orb" style={{ width: '400px', height: '400px', background: '#06b6d4', bottom: '-50px', right: '-50px', animationDelay: '2s' }} />
</div>
{/* Sidebar */}
{sidebarOpen && (
<aside className="relative z-10 w-72 glass border-r border-pal-border flex flex-col">
{/* New chat button */}
<div className="p-3">
<button onClick={newChat} className="w-full flex items-center gap-2 px-3 py-2.5 rounded-xl glass-card hover:border-pal-accent/30 transition-all text-sm text-pal-text font-medium">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 5v14M5 12h14"/></svg>
New Chat
</button>
</div>
{/* Nav */}
<nav className="px-2 space-y-0.5">
{([
['chat', '💬', 'Chat'],
['teach', '📚', 'Teach'],
['learn', '📖', 'Learn Text'],
['dream', '🌙', 'Dream'],
['stats', '📊', 'Statistics'],
] as [SidebarTab, string, string][]).map(([t, icon, label]) => (
<button key={t} onClick={() => setTab(t)}
className={`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-all ${
tab === t ? 'glass-card text-pal-text font-medium' : 'text-pal-muted hover:text-pal-text'
}`}>
<span>{icon}</span> {label}
</button>
))}
</nav>
{/* Connection status */}
<div className="mt-auto p-3 border-t border-pal-border">
<div className="flex items-center gap-2 mb-2">
<div className={`w-2 h-2 rounded-full ${api.connected ? 'bg-pal-green' : 'bg-pal-red'}`}>
{api.connected && <div className="w-2 h-2 rounded-full bg-pal-green animate-ping" />}
</div>
<span className="text-xs text-pal-muted">{api.connected ? 'Connected' : 'Offline'}</span>
</div>
<p className="text-[10px] text-pal-muted">PALIMPSESTE · No GPU · 0 weights</p>
<p className="text-[10px] text-pal-muted">Philippe-Antoine Robert · 2026</p>
</div>
</aside>
)}
{/* Main content */}
<main className="relative z-10 flex-1 flex flex-col">
{/* Top bar */}
<header className="flex items-center justify-between px-4 py-2.5 border-b border-pal-border glass">
<div className="flex items-center gap-3">
<button onClick={() => setSidebarOpen(!sidebarOpen)}
className="p-1.5 rounded-lg hover:bg-pal-card text-pal-muted hover:text-pal-text transition-all">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 12h18M3 6h18M3 18h18"/></svg>
</button>
<span className="text-sm font-bold gradient-text">PALIMPSESTE</span>
<span className="text-[10px] px-1.5 py-0.5 rounded-full bg-pal-accent/15 text-pal-accent font-semibold">BPE</span>
</div>
{api.metrics && (
<div className="hidden md:flex items-center gap-3 text-xs text-pal-muted">
<span>D={api.metrics.model.D.toLocaleString()}</span>
<span>·</span>
<span>|M|={api.metrics.model.n_traces.toLocaleString()}</span>
</div>
)}
</header>
{/* Content area */}
{tab === 'chat' && (
<>
{/* Messages */}
<div ref={scrollRef} className="flex-1 overflow-y-auto">
{messages.length === 0 ? (
<div className="h-full flex flex-col items-center justify-center px-6">
<div className="text-5xl mb-4 animate-float">🧠</div>
<h1 className="text-2xl font-bold gradient-text mb-1">PALIMPSESTE</h1>
<p className="text-sm text-pal-muted mb-8">A self-referential hypervectorial cortex</p>
<div className="grid grid-cols-2 gap-2 max-w-lg w-full">
{SUGGESTIONS.map(s => (
<button key={s.q} onClick={() => setInput(s.q)}
className="flex items-center gap-2 p-3 rounded-xl glass-card hover:border-pal-accent/30 transition-all text-left">
<span className="text-lg">{s.icon}</span>
<div>
<div className="text-xs font-medium text-pal-text">{s.title}</div>
<div className="text-[10px] text-pal-muted truncate">{s.q}</div>
</div>
</button>
))}
</div>
</div>
) : (
<div className="max-w-3xl mx-auto px-4 py-6 space-y-6">
{messages.map(msg => (
<div key={msg.id} className={`flex gap-3 ${msg.role === 'user' ? 'justify-end' : ''} animate-slide-up`}>
{msg.role === 'palimpseste' && (
<div className="w-8 h-8 rounded-full bg-gradient-to-br from-pal-accent to-pal-accent2 flex items-center justify-center text-sm flex-shrink-0">
🧠
</div>
)}
<div className={`max-w-[80%] ${msg.role === 'user' ? 'order-1' : ''}`}>
<div className={`rounded-2xl px-4 py-3 ${
msg.role === 'user'
? 'bg-gradient-to-br from-pal-accent/30 to-pal-accent/10 border border-pal-accent/30'
: 'glass border border-pal-border'
}`}>
<p className="text-sm text-pal-text whitespace-pre-wrap break-words">{msg.text}</p>
{msg.role === 'palimpseste' && msg.source && (
<div className="mt-2 pt-2 border-t border-pal-border/50">
<div className="flex items-center justify-between gap-2">
<SourceBadge source={msg.source} confidence={msg.confidence ?? 0} />
{msg.elapsed_ms !== undefined && (
<span className="text-[10px] text-pal-muted font-mono">{msg.elapsed_ms < 1 ? '<1' : msg.elapsed_ms.toFixed(0)}ms</span>
)}
</div>
</div>
)}
</div>
</div>
{msg.role === 'user' && (
<div className="w-8 h-8 rounded-full bg-pal-card flex items-center justify-center text-sm flex-shrink-0">
🧑
</div>
)}
</div>
))}
{api.loading && (
<div className="flex gap-3">
<div className="w-8 h-8 rounded-full bg-gradient-to-br from-pal-accent to-pal-accent2 flex items-center justify-center text-sm">🧠</div>
<div className="glass border border-pal-border rounded-2xl px-4 py-3">
<div className="flex gap-1.5">
<span className="w-2 h-2 rounded-full bg-pal-accent animate-bounce" style={{ animationDelay: '0ms' }} />
<span className="w-2 h-2 rounded-full bg-pal-accent animate-bounce" style={{ animationDelay: '150ms' }} />
<span className="w-2 h-2 rounded-full bg-pal-accent animate-bounce" style={{ animationDelay: '300ms' }} />
</div>
</div>
</div>
)}
</div>
)}
</div>
{/* Input bar */}
<div className="border-t border-pal-border glass px-4 py-3">
<div className="max-w-3xl mx-auto flex gap-2 items-end">
<textarea
value={input}
onChange={e => setInput(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend() } }}
placeholder="Message PALIMPSESTE..."
rows={1}
className="flex-1 bg-pal-surface border border-pal-border rounded-2xl px-4 py-3 text-sm text-pal-text placeholder:text-pal-muted focus:outline-none focus:border-pal-accent/40 transition-all resize-none max-h-32"
style={{ minHeight: '46px' }}
/>
<button onClick={handleSend} disabled={!input.trim() || api.loading}
className="p-3 rounded-2xl bg-gradient-to-br from-pal-accent to-pal-accent2 text-white transition-all hover:scale-105 hover:glow-accent disabled:opacity-30 disabled:cursor-not-allowed">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg>
</button>
</div>
<p className="text-center text-[10px] text-pal-muted mt-1.5">
PALIMPSESTE can make mistakes. No weights, no gradient, no GPU.
</p>
</div>
</>
)}
{/* TEACH TAB */}
{tab === 'teach' && (
<div className="flex-1 overflow-y-auto p-6">
<div className="max-w-lg mx-auto space-y-4">
<h2 className="text-lg font-bold text-pal-text flex items-center gap-2">📚 Teach PALIMPSESTE</h2>
<p className="text-sm text-pal-muted">Teach new facts instantly. O(1) memory write, immediately retrievable.</p>
<input value={teachQ} onChange={e => setTeachQ(e.target.value)} onKeyDown={e => e.key === 'Enter' && handleTeach()}
placeholder="Question" className="w-full bg-pal-surface border border-pal-border rounded-xl px-4 py-2.5 text-sm text-pal-text placeholder:text-pal-muted focus:outline-none focus:border-pal-green/40" />
<input value={teachA} onChange={e => setTeachA(e.target.value)} onKeyDown={e => e.key === 'Enter' && handleTeach()}
placeholder="Answer" className="w-full bg-pal-surface border border-pal-border rounded-xl px-4 py-2.5 text-sm text-pal-text placeholder:text-pal-muted focus:outline-none focus:border-pal-green/40" />
<button onClick={handleTeach} disabled={!teachQ.trim() || !teachA.trim() || api.loading}
className="w-full py-2.5 rounded-xl bg-gradient-to-r from-pal-green to-pal-accent2 text-white font-semibold text-sm transition-all hover:scale-[1.02] disabled:opacity-30">
⚡ Teach Instantly
</button>
{teachHistory.map((h, i) => (
<div key={i} className="p-3 rounded-xl glass-card animate-slide-up">
<div className="text-sm text-pal-text">{h.q} → <span className="text-pal-green font-medium">{h.a}</span></div>
<div className="text-[10px] text-pal-muted mt-0.5">+{h.tokens} tokens</div>
</div>
))}
</div>
</div>
)}
{/* LEARN TAB */}
{tab === 'learn' && (
<div className="flex-1 overflow-y-auto p-6">
<div className="max-w-lg mx-auto space-y-4">
<h2 className="text-lg font-bold text-pal-text flex items-center gap-2">📖 Instant Expertise</h2>
<p className="text-sm text-pal-muted">Paste any text. PALIMPSESTE becomes an expert in milliseconds.</p>
<textarea value={learnText} onChange={e => setLearnText(e.target.value)} placeholder="Paste a document, article, or any text..." rows={8}
className="w-full bg-pal-surface border border-pal-border rounded-xl px-4 py-2.5 text-sm text-pal-text placeholder:text-pal-muted focus:outline-none focus:border-pal-accent2/40 resize-none" />
<button onClick={handleLearn} disabled={!learnText.trim() || api.loading}
className="w-full py-2.5 rounded-xl bg-gradient-to-r from-pal-accent2 to-pal-green text-white font-semibold text-sm transition-all hover:scale-[1.02] disabled:opacity-30">
⚡ Learn Instantly
</button>
{learnResult && !learnResult.error && (
<div className="p-3 rounded-xl glass-card border-pal-accent2/20 animate-slide-up">
<div className="text-sm font-semibold text-pal-green mb-1">✓ Learned {learnResult.n_facts} facts in {learnResult.n_seconds}s</div>
{learnResult.facts?.map((f: any, i: number) => (
<div key={i} className="text-xs text-pal-text mt-1"><span className="text-pal-accent2">Q:</span> {f.q}<br/><span className="text-pal-green">A:</span> {f.a?.slice(0, 80)}</div>
))}
</div>
)}
</div>
</div>
)}
{/* DREAM TAB */}
{tab === 'dream' && (
<div className="flex-1 overflow-y-auto p-6">
<div className="max-w-lg mx-auto space-y-4">
<h2 className="text-lg font-bold text-pal-text flex items-center gap-2">🌙 Dream Consolidation</h2>
<p className="text-sm text-pal-muted">When idle, PALIMPSESTE replays memory, discovers concepts, and gets smarter autonomously.</p>
<button onClick={handleDream} disabled={api.loading}
className="w-full py-2.5 rounded-xl bg-gradient-to-r from-pal-accent to-pal-accent2 text-white font-semibold text-sm transition-all hover:scale-[1.02] hover:glow-accent disabled:opacity-30">
🌙 Trigger Dream
</button>
{dreamResult && !dreamResult.error && (
<div className="p-3 rounded-xl glass-card border-pal-accent/20 animate-slide-up">
<div className="text-sm font-semibold text-pal-accent">✓ {dreamResult.n_concepts_extracted} concepts discovered</div>
<div className="text-xs text-pal-muted mt-1">in {dreamResult.n_seconds}s · {dreamResult.n_total_concepts} total</div>
{dreamResult.concept_labels?.length > 0 && (
<div className="flex flex-wrap gap-1 mt-2">
{dreamResult.concept_labels.map((l: string, i: number) => (
<span key={i} className="text-[10px] px-2 py-0.5 rounded-full bg-pal-accent/10 text-pal-accent">{l}</span>
))}
</div>
)}
</div>
)}
</div>
</div>
)}
{/* STATS TAB */}
{tab === 'stats' && api.metrics && (
<div className="flex-1 overflow-y-auto p-6">
<div className="max-w-lg mx-auto space-y-3">
<h2 className="text-lg font-bold text-pal-text">📊 Statistics</h2>
<div className="grid grid-cols-2 gap-2">
<StatCard label="Dimension (D)" value={api.metrics.model.D.toLocaleString()} />
<StatCard label="Memory Traces" value={api.metrics.model.n_traces.toLocaleString()} />
<StatCard label="Vocab" value={api.metrics.model.vocab_size.toLocaleString()} />
<StatCard label="Context Window" value={api.metrics.model.context_window.toString()} />
<StatCard label="Kernel Radius" value={api.metrics.config.kernel_radius.toString()} />
<StatCard label="Temperature" value={api.metrics.config.temperature.toString()} />
<StatCard label="Turns" value={api.metrics.conversation.turns.toString()} />
<StatCard label="Mean Weight" value={api.metrics.memory.mean_weight.toFixed(3)} />
</div>
<div className="p-3 rounded-xl glass-card">
<div className="text-[10px] text-pal-muted uppercase font-medium mb-1">Theoretical Capacity</div>
<div className="text-lg font-bold gradient-text">2^{(api.metrics.model.theoretical_capacity_log2 / 3.32).toFixed(0)}</div>
<div className="text-[10px] text-pal-muted">≈ 10^{api.metrics.model.theoretical_capacity_log2.toFixed(0)} associations</div>
</div>
</div>
</div>
)}
{tab === 'stats' && !api.metrics && (
<div className="flex-1 flex items-center justify-center text-pal-muted text-sm">Loading statistics...</div>
)}
</main>
</div>
)
}
function StatCard({ label, value }: { label: string; value: string }) {
return (
<div className="p-3 rounded-xl glass-card">
<div className="text-[10px] text-pal-muted uppercase font-medium">{label}</div>
<div className="text-lg font-bold text-pal-text">{value}</div>
</div>
)
}
|