Spaces:
Sleeping
Sleeping
File size: 17,488 Bytes
4888d8d e5f49d0 4888d8d e5f49d0 001f64b e5f49d0 001f64b e5f49d0 001f64b e5f49d0 001f64b e5f49d0 001f64b e5f49d0 001f64b e5f49d0 001f64b e5f49d0 8858730 83d7c63 e5f49d0 8858730 e5f49d0 a0d3ca3 e5f49d0 83d7c63 e5f49d0 ff2f44c e5f49d0 ff2f44c e5f49d0 ff2f44c e5f49d0 ff2f44c e5f49d0 ff2f44c e5f49d0 ff2f44c e5f49d0 ff2f44c e5f49d0 001f64b e5f49d0 4888d8d e5f49d0 4888d8d e5f49d0 4888d8d e5f49d0 8858730 e5f49d0 a1dc6e0 e5f49d0 bf72839 e5f49d0 4888d8d e5f49d0 a1dc6e0 e5f49d0 92d32b4 e5f49d0 e4e3c4c e5f49d0 4888d8d e5f49d0 4888d8d e5f49d0 e6fe14d e5f49d0 4888d8d e5f49d0 4888d8d e5f49d0 92d32b4 e5f49d0 92d32b4 e5f49d0 4888d8d e5f49d0 4888d8d e5f49d0 bf72839 e5f49d0 bf72839 e5f49d0 4888d8d e5f49d0 4888d8d e5f49d0 4888d8d e5f49d0 4888d8d e5f49d0 b90e515 7e26ff7 e5f49d0 b90e515 e5f49d0 7e26ff7 e5f49d0 a1dc6e0 a5a5683 e5f49d0 a5a5683 e5f49d0 a5a5683 f4215ce a5a5683 4888d8d 90204c6 a5a5683 4888d8d 7e26ff7 4888d8d e5f49d0 4888d8d b90e515 4888d8d e5f49d0 4888d8d e5f49d0 4888d8d b90e515 e5a9770 e5f49d0 edb7ba2 e5f49d0 edb7ba2 e5a9770 e5f49d0 edb7ba2 e5f49d0 edb7ba2 e5a9770 4888d8d e5f49d0 4888d8d dc49487 4888d8d 001f64b 4888d8d e5f49d0 4888d8d e5f49d0 | 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 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 | // src/App.js
import React, { useState, useMemo } from "react";
import { login, streamChat } from "./api";
import "./App.css";
import ReactMarkdown from "react-markdown";
import remarkMath from "remark-math";
import rehypeKatex from "rehype-katex";
import "katex/dist/katex.min.css";
import remarkGfm from "remark-gfm";
// ---------------------------------------------------------------------------
// QUOTES
// ---------------------------------------------------------------------------
const LOGIC_SAYINGS = [
"Logic is the compass; reason is the journey.",
"Logic doesn\u2019t tell you where to go\u2014only how not to get lost.",
"Emotion starts the fire; logic builds the fireplace.",
"Logic is truth with the noise removed.",
"Where logic ends, belief begins.",
"Logic is the discipline of refusing to lie to yourself.",
"A logical mind fears no question.",
"Logic is patience armed with structure.",
"Without logic, intelligence is just decoration.",
"Logic turns confusion into coordinates.",
"Logic is thinking that survives inspection.",
"Feelings persuade; logic convinces.",
"Logic is the skeleton beneath every solid idea.",
"Logic is humility formalized.",
"Logic is the courage to follow conclusions you don\u2019t like.",
"Logic is what remains when excuses are removed.",
"Logic is slow thinking that wins.",
"Logic is the art of necessary consequences.",
"Logic is not cold\u2014it\u2019s honest.",
"Logic asks \u2018must it be so?\u2019",
"Logic is the bridge between assumptions and reality.",
"Logic is doubt with a method.",
"Logic is reason refusing shortcuts.",
"Logic is clarity earned, not assumed.",
"Logic is the enemy of convenient nonsense.",
"Logic is freedom from contradiction.",
"Logic is the courage to say \u2018I was wrong.\u2019",
"Logic is precision applied to belief.",
"Logic is the difference between opinion and argument.",
"Logic is trust in structure over impulse.",
"Logic is thought that can be audited.",
"Logic is the firewall against self-deception.",
"Logic is truth, step by step.",
"Logic is thinking that welcomes scrutiny.",
"Logic is the difference between sounding right and being right.",
"Logic is belief with a warranty.",
"Logic is calm thinking in loud situations.",
"Logic is the architecture of understanding.",
"Logic is the slow weapon against fast lies.",
"Logic is consistency made explicit.",
"Logic is explanation that doesn\u2019t flinch.",
"Logic is truth under constraints.",
"Logic is evidence wearing syntax.",
"Logic is the guardrail of intelligence.",
"Logic is the art of unavoidable conclusions.",
"Logic is reasoning that respects reality.",
"Logic is the structure beneath insight.",
"Logic is understanding without shortcuts.",
"Logic is thought with integrity.",
"Logic is the science of consistency.",
"Logic is respect\u2014for truth, for thought, and for consequence.",
];
// ---------------------------------------------------------------------------
// HELPERS
// ---------------------------------------------------------------------------
function fixCurrencyInMath(text) {
let result = '';
let i = 0;
const len = text.length;
while (i < len) {
// Display math: $$...$$
if (text[i] === '$' && i + 1 < len && text[i + 1] === '$' &&
(i === 0 || text[i - 1] !== '\\')) {
let j = i + 2, close = -1;
while (j < len - 1) {
if (text[j] === '$' && text[j + 1] === '$' && text[j - 1] !== '\\') { close = j; break; }
j++;
}
if (close !== -1) {
let c = text.slice(i + 2, close).replace(/\\\$/g, '\\dollar{}');
result += '$$' + c + '$$';
i = close + 2;
continue;
}
}
// Inline math: $...$
if (text[i] === '$' && (i === 0 || text[i - 1] !== '\\') &&
(i + 1 >= len || text[i + 1] !== '$')) {
let j = i + 1, close = -1;
while (j < len) {
if (text[j] === '$' && text[j - 1] !== '\\' &&
(j + 1 >= len || text[j + 1] !== '$')) { close = j; break; }
j++;
}
if (close !== -1) {
let c = text.slice(i + 1, close).replace(/\\\$/g, '\\dollar{}');
result += '$' + c + '$';
i = close + 1;
continue;
}
}
result += text[i];
i++;
}
return result;
}
function normalizeLatex(text) {
if (!text) return "";
let n = text;
n = n.replace(/\\\[(.+?)\\\]/gs, (_, i) => `$$${i}$$`);
n = n.replace(/\\\((.+?)\\\)/gs, (_, i) => `$${i}$`);
n = n.replace(/\$\$\$\$/g, "$$");
n = n.replace(/\$\$\$/g, "$$");
n = n.replace(/\\begin\{align\*?\}/g, "\\begin{aligned}");
n = n.replace(/\\end\{align\*?\}/g, "\\end{aligned}");
n = n.replace(/\\begin\{equation\*?\}/g, "");
n = n.replace(/\\end\{equation\*?\}/g, "");
n = n.replace(/\\begin\{gather\*?\}/g, "\\begin{gathered}");
n = n.replace(/\\end\{gather\*?\}/g, "\\end{gathered}");
n = n.replace(/\\begin\{eqnarray\*?\}/g, "\\begin{aligned}");
n = n.replace(/\\end\{eqnarray\*?\}/g, "\\end{aligned}");
n = fixCurrencyInMath(n);
n = n.replace(/\$\$([^$]+?)\$\$/gs, (match, inner) => {
const t = inner.trim();
const hasAlign = /[^\\]&/.test(t) || t.startsWith("&");
const hasEnv = /\\begin\{/.test(t);
if (hasAlign && !hasEnv) return `$$\\begin{aligned}\n${t}\n\\end{aligned}$$`;
return `$$${t}$$`;
});
return n;
}
// ---------------------------------------------------------------------------
// COLLAPSIBLE DEBUG SECTION
// ---------------------------------------------------------------------------
function DebugExpander({ title, defaultOpen = false, children }) {
const [open, setOpen] = useState(defaultOpen);
return (
<div style={{ marginBottom: 12 }}>
<button
onClick={() => setOpen(!open)}
style={{
width: "100%", textAlign: "left", padding: "8px 12px",
background: open ? "#e8f4f8" : "#fff", border: "1px solid #ccc",
borderRadius: 4, cursor: "pointer", display: "flex",
alignItems: "center", justifyContent: "space-between",
fontWeight: 600, color: "#1a1a1a", fontSize: "0.9em",
}}
>
<span>{title}</span>
<span style={{ fontSize: "1.2em", transform: open ? "rotate(90deg)" : "rotate(0deg)", transition: "transform 0.2s", display: "inline-block" }}>▶</span>
</button>
{open && (
<div style={{ marginTop: 8, padding: 10, background: "#fff", border: "1px solid #e2e2e2", borderRadius: 4 }}>
{children}
</div>
)}
</div>
);
}
// ---------------------------------------------------------------------------
// MESSAGE BUBBLE
// ---------------------------------------------------------------------------
function Message({ message }) {
const isUser = message.role === "user";
const [showDebug, setShowDebug] = useState(false);
const stripFences = React.useCallback((t) => {
if (typeof t !== "string") return "";
return t.replace(/```\s*json\s*/gi, "").replace(/```/g, "").trim();
}, []);
const isThinking =
!isUser && message.thinking && (!message.text?.trim() || message.statusText);
const normalizedText = useMemo(
() => normalizeLatex(message.text || ""),
[message.text]
);
return (
<div className={`message ${isUser ? "user" : "assistant"}`}>
<div className="bubble">
{isThinking ? (
<div className="thinking-container">
<div className="thinking-dots"><span /><span /><span /></div>
{message.statusText && <div className="thinking-status">{message.statusText}</div>}
</div>
) : (
<ReactMarkdown
className="markdown-body"
remarkPlugins={[remarkMath, remarkGfm]}
rehypePlugins={[[rehypeKatex, { strict: "ignore", throwOnError: false, trust: true, errorColor: "#e2e8f0", macros: { "\\dollar": "\\$" } }]]}
skipHtml={false}
breaks
>
{normalizedText}
</ReactMarkdown>
)}
</div>
{/* Debug panel */}
{!isUser && message.debug && (
<>
<button
className="debug-toggle"
onClick={() => setShowDebug((v) => !v)}
style={{ marginTop: 8, fontSize: "0.85em", padding: "4px 10px", background: "#f0f0f0", border: "1px solid #ccc", borderRadius: 4, cursor: "pointer" }}
>
{showDebug ? "Hide Prolog Queries" : "Show Prolog Queries"}
</button>
{showDebug && (
<div className="debug-panel" style={{ marginTop: 10, padding: 12, background: "#f8f8f8", border: "1px solid #ddd", borderRadius: 6, fontSize: "0.9em", color: "#1a1a1a" }}>
<h4 style={{ marginTop: 0, marginBottom: 10 }}>Prolog Query Analysis</h4>
{message.debug.llm_analysis && (
<DebugExpander title="Generated Queries">
<pre style={{ background: "#fff", padding: 8, borderRadius: 4, fontSize: "0.9em", overflowX: "auto", color: "#1a1a1a", margin: 0 }}>
{stripFences(message.debug.llm_analysis)}
</pre>
</DebugExpander>
)}
{message.debug.predicates_queried?.length > 0 && (
<DebugExpander title={`Predicates Queried (${message.debug.predicates_queried.length})`}>
<span style={{ color: "#0066cc", fontWeight: 500 }}>
{message.debug.predicates_queried.join(", ")}
</span>
</DebugExpander>
)}
{message.debug.queries_executed?.length > 0 && (
<DebugExpander title={`Executed Queries (${message.debug.queries_executed.length})`}>
<ul style={{ marginTop: 5, paddingLeft: 20, marginBottom: 0 }}>
{message.debug.queries_executed.map((q, i) => (
<li key={i} style={{ marginBottom: 5 }}>
<code style={{ background: "#e8f4f8", padding: "2px 6px", borderRadius: 3, fontSize: "0.9em" }}>{q.query}</code>{" "}
<span style={{ color: "#333" }}>{"\u2192"} {q.results_count} result{q.results_count !== 1 ? "s" : ""}</span>
</li>
))}
</ul>
</DebugExpander>
)}
{message.debug.evidence && (
<DebugExpander title={`Evidence (${(message.debug.evidence.facts || []).length} facts)`}>
<div>
{message.debug.evidence.fact_bindings?.length > 0 && (
<div style={{ marginBottom: 10 }}>
<strong>Structured bindings:</strong> {message.debug.evidence.fact_bindings.length}
<pre style={{ background: "#fff", padding: 8, borderRadius: 4, fontSize: "0.85em", overflowX: "auto", marginTop: 6 }}>
{JSON.stringify(message.debug.evidence.fact_bindings, null, 2)}
</pre>
</div>
)}
</div>
</DebugExpander>
)}
<div style={{ marginTop: 10, paddingTop: 10, borderTop: "1px solid #ddd" }}>
<strong>Total Results:</strong>{" "}
<span style={{ color: "#00aa00", fontWeight: "bold" }}>{message.debug.total_results || 0}</span>
</div>
</div>
)}
</>
)}
</div>
);
}
// ---------------------------------------------------------------------------
// MAIN APP
// ---------------------------------------------------------------------------
function App() {
const randomSaying = useMemo(
() => LOGIC_SAYINGS[Math.floor(Math.random() * LOGIC_SAYINGS.length)],
[]
);
// Auth
const [token, setToken] = useState(null);
const [authError, setAuthError] = useState(null);
const [loginForm, setLoginForm] = useState({ username: "", password: "" });
// Chat
const [messages, setMessages] = useState([]);
const [input, setInput] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
// Session trigger for new chat
const [sessionTrigger, setSessionTrigger] = useState(0);
const sessionId = useMemo(() => {
try { return crypto.randomUUID(); } catch {}
return `sid-${Date.now()}-${Math.random().toString(16).slice(2)}`;
}, [sessionTrigger]); // eslint-disable-line react-hooks/exhaustive-deps
// Auto-scroll
React.useEffect(() => {
const c = document.querySelector(".messages");
if (c) c.scrollTop = c.scrollHeight;
}, [messages]);
// ββ Login ββ
async function handleLogin(e) {
e.preventDefault();
setAuthError(null);
try {
const res = await login(loginForm.username, loginForm.password);
setToken(res.token);
} catch (err) {
setAuthError(err.message || "Login failed");
}
}
// ββ New chat ββ
function handleNewChat() {
setMessages([]);
setInput("");
setError(null);
setSessionTrigger((p) => p + 1);
}
// ββ Send message + stream response ββ
async function handleSend(e) {
if (e) e.preventDefault();
if (!input.trim() || loading || !token) return;
const userMsg = { role: "user", text: input.trim() };
const assistantMsg = { role: "assistant", text: "", debug: null, thinking: true, statusText: "" };
const newMessages = [...messages, userMsg, assistantMsg];
setMessages(newMessages);
setInput("");
setError(null);
setLoading(true);
try {
const history = newMessages.map((m) => ({ role: m.role, content: m.text }));
await streamChat(
userMsg.text,
history,
token,
(chunk) => {
if (assistantMsg.thinking && !assistantMsg.text?.trim()) {
assistantMsg.text = chunk;
assistantMsg.thinking = false;
assistantMsg.statusText = "";
} else {
assistantMsg.text += chunk;
}
setMessages([...newMessages]);
},
sessionId,
(statusMsg) => {
if (!assistantMsg.text?.trim()) {
assistantMsg.statusText = statusMsg;
assistantMsg.thinking = true;
setMessages([...newMessages]);
}
},
(debugData) => {
assistantMsg.debug = debugData;
setMessages([...newMessages]);
}
);
assistantMsg.thinking = false;
assistantMsg.statusText = "";
setMessages([...newMessages]);
} catch (err) {
assistantMsg.thinking = false;
assistantMsg.text += `\n[Error: ${err.message}]`;
setMessages([...newMessages]);
} finally {
setLoading(false);
}
}
// ββ Login screen ββ
if (!token) {
return (
<div className="app-root">
<header className="header">
<h1 className="header-title">Prolog AI</h1>
</header>
<main className="main login">
<form className="login-form" onSubmit={handleLogin}>
<h2>Sign In</h2>
<input type="text" placeholder="Username" value={loginForm.username}
onChange={(e) => setLoginForm({ ...loginForm, username: e.target.value })} />
<input type="password" placeholder="Password" value={loginForm.password}
onChange={(e) => setLoginForm({ ...loginForm, password: e.target.value })} />
<button type="submit">Log In</button>
{authError && <div className="error">{authError}</div>}
</form>
</main>
</div>
);
}
// ββ Chat UI ββ
return (
<div className="app-root">
<header className="header">
<h1 className="header-title">Prolog AI</h1>
<div className="header-actions">
<button className="btn-secondary" onClick={handleNewChat} title="New Chat Session">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M12 5v14M5 12h14" />
</svg>
</button>
<button className="logout-btn" onClick={() => setToken(null)} title="Logout">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
<polyline points="16 17 21 12 16 7" />
<line x1="21" y1="12" x2="9" y2="12" />
</svg>
</button>
</div>
</header>
<div className="app-container">
<main className="main">
<div className="messages">
{messages.map((msg, idx) => (
<Message key={idx} message={msg} />
))}
</div>
{error && <div className="error">{error}</div>}
<form className="input-row" onSubmit={handleSend}>
<textarea
placeholder={randomSaying}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleSend(); }
}}
disabled={loading}
rows="2"
/>
</form>
</main>
</div>
</div>
);
}
export default App;
|