prolog_llm / src /App.js
fraudTech's picture
fix: LaTeX rendering for currency dollar signs inside math spans
8858730
Raw History Blame Contribute Delete
17.5 kB
// 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" }}>&#9654;</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;