Spaces:
Sleeping
Sleeping
Download web/src/App.tsx from DeepThoughtAI/evo-frontend: direct link, hf CLI and curl.
- Browser
- Download file 86.3 kB
-
https://huggingface.co/spaces/DeepThoughtAI/evo-frontend/resolve/main/web/src/App.tsx
- Command line
-
hf download hf://spaces/DeepThoughtAI/evo-frontend/web/src/App.tsx
-
curl -L -o App.tsx https://huggingface.co/spaces/DeepThoughtAI/evo-frontend/resolve/main/web/src/App.tsx
86.3 kB
import React, { useState, useRef, useEffect, useMemo, useCallback } from 'react';
import ReactMarkdown, { defaultUrlTransform } from 'react-markdown';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import remarkMath from 'remark-math';
import remarkGfm from 'remark-gfm';
import rehypeKatex from 'rehype-katex';
import rehypeRaw from 'rehype-raw';
import 'katex/dist/katex.min.css';
import katex from 'katex';
import Login from './Login';
import './App.css';
const LOGIC_SAYINGS = [
"Logic is disciplined honesty",
"Logic tames intuition",
"Logic survives scrutiny",
"Logic resists wishful thinking",
"Logic clarifies chaos",
"Logic enforces consistency",
"Logic demands consequences",
"Logic hates contradiction",
"Logic respects structure",
"Logic questions assumptions",
"Logic over loud opinions",
"Logic scales beyond intuition",
"Logic is structured doubt",
"Logic follows necessity",
"Logic earns trust",
"Logic trims nonsense",
"Logic values implication",
"Logic prevents self-deception",
"Logic is careful thinking",
"Logic disciplines belief",
"Logic outlives emotion",
"Logic defines fairness",
"Logic reveals errors",
"Logic needs no applause",
"Logic is patient clarity",
"Logic refuses shortcuts",
"Logic enforces coherence",
"Logic invites verification",
"Logic keeps promises",
"Logic respects evidence",
"Logic cuts cleanly",
"Logic exposes contradictions",
"Logic is structured reasoning",
"Logic defeats ambiguity",
"Logic rejects special pleading",
"Logic anchors truth",
"Logic strengthens arguments",
"Logic filters belief",
"Logic withstands pressure",
"Logic enables understanding",
"Logic is mental hygiene",
"Logic values consistency",
"Logic guards intelligence",
"Logic is intellectual integrity",
"Logic reveals necessity",
"Logic is consequence-aware",
"Logic clarifies premises",
"Logic enforces discipline",
"Logic refines thought",
"Logic avoids contradiction",
"Logic resists manipulation",
"Logic empowers truth",
"Logic disciplines intuition",
"Logic respects implication",
"Logic is rigorous thinking",
"Logic survives opposition",
"Logic rejects ambiguity",
"Logic is systematic clarity",
"Logic curbs bias",
"Logic anchors reasoning",
"Logic exposes fallacies",
"Logic enforces structure",
"Logic is formal honesty",
"Logic strengthens insight",
"Logic trims assumptions",
"Logic invites challenge",
"Logic prefers coherence",
"Logic defeats confusion",
"Logic remains impartial",
"Logic respects consequences",
"Logic makes sense durable",
"Logic tests belief",
"Logic values precision",
"Logic demands justification",
"Logic refines arguments",
"Logic guards truth",
"Logic stabilizes thought",
"Logic is disciplined skepticism",
"Logic clarifies meaning",
"Logic enforces necessity",
"Logic rejects contradictions",
"Logic sustains reasoning",
"Logic keeps ideas honest",
"Logic enforces fairness",
"Logic structures understanding",
"Logic prevents nonsense",
"Logic respects reality",
"Logic rejects inconsistency",
"Logic sharpens clarity",
"Logic enables precision",
"Logic stabilizes belief",
"Logic resists illusion",
"Logic enforces truthfulness",
"Logic exposes inconsistency",
"Logic refines clarity",
"Logic demands coherence",
"Logic preserves meaning",
"Logic strengthens truth",
"Logic clarifies necessity",
"Logic enforces rationality",
];
// Eye-health optimized warm syntax highlighting theme
const terminalTheme = {
'code[class*="language-"]': {
color: '#c9b8a3',
fontFamily: '"SF Mono", "Monaco", "Cascadia Code", "Consolas", monospace',
fontSize: '0.9em',
background: '#1a1614',
},
'pre[class*="language-"]': {
color: '#c9b8a3',
fontFamily: '"SF Mono", "Monaco", "Cascadia Code", "Consolas", monospace',
fontSize: '0.9em',
background: '#1a1614',
padding: '1rem',
margin: '0.75rem 0',
overflow: 'auto',
border: '1px solid #3a342e',
borderRadius: '6px',
},
comment: {
color: '#6e5d4d',
fontStyle: 'italic',
},
prolog: { color: '#6e5d4d' },
doctype: { color: '#6e5d4d' },
cdata: { color: '#6e5d4d' },
punctuation: { color: '#a89784' },
property: { color: '#c9b8a3' },
tag: { color: '#d4a574' },
boolean: { color: '#b89968' },
number: { color: '#b89968' },
constant: { color: '#c9b8a3' },
symbol: { color: '#c9b8a3' },
deleted: { color: '#d49999' },
selector: { color: '#d4a574' },
'attr-name': { color: '#d4a574' },
string: { color: '#9d8264' },
char: { color: '#9d8264' },
builtin: { color: '#c9b8a3' },
inserted: { color: '#9d8264' },
operator: { color: '#a89784' },
entity: { color: '#d4a574' },
url: { color: '#8b7355' },
'.language-css .token.string': { color: '#9d8264' },
'.style .token.string': { color: '#9d8264' },
variable: { color: '#c9b8a3' },
atrule: { color: '#d4a574' },
'attr-value': { color: '#9d8264' },
function: { color: '#d4a574' },
'class-name': { color: '#d4a574' },
keyword: { color: '#b89968', fontWeight: 'bold' },
regex: { color: '#9d8264' },
important: { color: '#d4a574', fontWeight: 'bold' },
};
// Light syntax highlighting theme
const lightCodeTheme = {
'code[class*="language-"]': {
color: '#383a42',
fontFamily: '"SF Mono", "Monaco", "Cascadia Code", "Consolas", monospace',
fontSize: '0.9em',
background: '#f0f0f0',
},
'pre[class*="language-"]': {
color: '#383a42',
fontFamily: '"SF Mono", "Monaco", "Cascadia Code", "Consolas", monospace',
fontSize: '0.9em',
background: '#f0f0f0',
padding: '1rem',
margin: '0.75rem 0',
overflow: 'auto',
border: '1px solid #dcdcdc',
borderRadius: '6px',
},
comment: { color: '#a0a1a7', fontStyle: 'italic' },
prolog: { color: '#a0a1a7' },
doctype: { color: '#a0a1a7' },
cdata: { color: '#a0a1a7' },
punctuation: { color: '#383a42' },
property: { color: '#4078f2' },
tag: { color: '#e45649' },
boolean: { color: '#986801' },
number: { color: '#986801' },
constant: { color: '#4078f2' },
symbol: { color: '#4078f2' },
deleted: { color: '#e45649' },
selector: { color: '#50a14f' },
'attr-name': { color: '#986801' },
string: { color: '#50a14f' },
char: { color: '#50a14f' },
builtin: { color: '#0184bc' },
inserted: { color: '#50a14f' },
operator: { color: '#383a42' },
entity: { color: '#986801' },
url: { color: '#0184bc' },
variable: { color: '#e45649' },
atrule: { color: '#0184bc' },
'attr-value': { color: '#50a14f' },
function: { color: '#4078f2' },
'class-name': { color: '#c18401' },
keyword: { color: '#a626a4', fontWeight: 'bold' },
regex: { color: '#50a14f' },
important: { color: '#e45649', fontWeight: 'bold' },
};
// Context used by out-of-component code renderers to pick the right syntax theme
const CodeThemeContext = React.createContext<object>(terminalTheme);
const allowDataImageUrl = (url: string): string => {
if (url.startsWith('data:image/')) {
return url;
}
return defaultUrlTransform(url);
};
const splitStreamingContent = (content: string): { safe: string; tail: string } => {
if (!content) {
return { safe: '', tail: '' };
}
let inCodeFence = false;
let codeFenceStartIndex = 0;
let inInlineMath = false;
let inDisplayMath = false;
let mathStartIndex = 0;
for (let i = 0; i < content.length; i += 1) {
if (content.startsWith('```', i)) {
if (!inCodeFence) {
inCodeFence = true;
codeFenceStartIndex = i;
} else {
inCodeFence = false;
}
i += 2;
continue;
}
if (inCodeFence) {
continue;
}
const char = content[i];
// Detect \begin{env}...\end{env} for display math environments BEFORE the generic
// escape-skip below (which would consume the 'b' in \begin and miss it).
// If the environment is unclosed (still streaming), treat it as an unsafe tail.
if (char === '\\' && !inDisplayMath && !inInlineMath && !inCodeFence &&
content.startsWith('\\begin{', i)) {
const endBrace = content.indexOf('}', i + 7);
if (endBrace !== -1) {
const envName = content.slice(i + 7, endBrace);
const baseEnv = envName.replace(/\*$/, ''); // strip trailing * for align*, etc.
const displayEnvNames = [
'aligned', 'align', 'equation', 'gather', 'multline',
'array', 'matrix', 'pmatrix', 'bmatrix', 'vmatrix', 'Vmatrix',
'cases', 'split', 'eqnarray',
];
if (displayEnvNames.includes(baseEnv)) {
const endPattern = `\\end{${envName}}`;
const endIdx = content.indexOf(endPattern, endBrace);
if (endIdx === -1) {
// \end{env} not yet received — keep as raw tail until it arrives
return {
safe: content.slice(0, i),
tail: content.slice(i),
};
}
// Complete block present — skip past \end{env} so the rest is scanned normally
i = endIdx + endPattern.length - 1;
continue;
}
}
}
if (char === '\\') {
i += 1;
continue;
}
if (!inInlineMath && content.startsWith('\\[', i)) {
if (!inDisplayMath) {
inDisplayMath = true;
mathStartIndex = i;
}
i += 1;
continue;
}
if (!inInlineMath && content.startsWith('\\]', i)) {
if (inDisplayMath) {
inDisplayMath = false;
}
i += 1;
continue;
}
if (!inInlineMath && content.startsWith('$$', i)) {
if (!inDisplayMath) {
inDisplayMath = true;
mathStartIndex = i;
} else {
inDisplayMath = false;
}
i += 1;
continue;
}
if (inDisplayMath) {
continue;
}
if (char === '$') {
if (!inInlineMath) {
inInlineMath = true;
mathStartIndex = i;
} else {
inInlineMath = false;
}
}
}
if (inInlineMath || inDisplayMath) {
return {
safe: content.slice(0, mathStartIndex),
tail: content.slice(mathStartIndex),
};
}
// Treat an unclosed code fence as unsafe — show as raw tail until it closes.
if (inCodeFence) {
return {
safe: content.slice(0, codeFenceStartIndex),
tail: content.slice(codeFenceStartIndex),
};
}
return { safe: content, tail: '' };
};
const normalizeUserLatex = (content: string): string => {
if (!content) {
return content;
}
let normalized = content;
const trimmed = normalized.trim();
// Support bare display-style square-bracket wrappers used by some users,
// e.g.:
// [y = (3x^2 - 2x + 1)e^x.]
// or multi-line:
// [
// y = (3x^2 - 2x + 1)e^x.
// ]
// Avoid converting JSON-like arrays or matrix literals handled elsewhere.
if (
trimmed.startsWith('[') &&
trimmed.endsWith(']') &&
!/^\[\s*\[/.test(trimmed) &&
/(?:=|\^|_|\\|[+\-*/]|\b(?:sin|cos|tan|log|ln|exp)\b)/.test(trimmed.slice(1, -1))
) {
const inner = trimmed.slice(1, -1).trim();
if (inner) {
return `$$${inner}$$`;
}
}
// Convert simple 2D array literals into LaTeX matrices, e.g. [[2,1],[1,2]].
normalized = normalized.replace(
/\[\s*\[[^[\]]+\](?:\s*,\s*\[[^[\]]+\])+\s*\]/g,
(raw) => {
try {
const parsed = JSON.parse(raw);
if (
!Array.isArray(parsed) ||
parsed.length === 0 ||
!parsed.every((row) => Array.isArray(row) && row.length > 0)
) {
return raw;
}
const width = (parsed[0] as any[]).length;
if (!parsed.every((row) => (row as any[]).length === width)) {
return raw; // not rectangular
}
if (
!parsed.every((row) =>
(row as any[]).every((cell) =>
typeof cell === 'number' || typeof cell === 'string' || typeof cell === 'boolean'
)
)
) {
return raw;
}
const body = parsed
.map((row) => (row as any[]).map((cell) => String(cell)).join(' & '))
.join(' \\\\ ');
return `$$\\begin{bmatrix}${body}\\end{bmatrix}$$`;
} catch {
return raw;
}
}
);
// Auto-close dangling $$ display-math blocks so KaTeX can render.
// Convert explicit LaTeX delimiters \( ... \) and \[ ... \].
normalized = normalized.replace(/\\\(([\s\S]*?)\\\)/g, (_m, expr) => `$${expr.trim()}$`);
normalized = normalized.replace(/\\\[([\s\S]*?)\\\]/g, (_m, expr) => `$$${expr.trim()}$$`);
// Wrap common block environments if user forgot $$ delimiters.
normalized = normalized.replace(
/\\begin\{(aligned|align\*?|alignat\*?|alignedat\*?|equation\*?|gather\*?|multline\*?|array|smallmatrix|matrix|pmatrix|bmatrix|Bmatrix|vmatrix|Vmatrix|cases|split|eqnarray\*?)\}[\s\S]*?\\end\{\1\}/g,
(m) => `$$${m}$$`
);
// Generic fallback for any bare \begin{env}...\end{env} block not already wrapped.
normalized = normalized.replace(
/(^|[^\$])\\begin\{([A-Za-z*]+)\}[\s\S]*?\\end\{\2\}/g,
(m, prefix) => {
const body = String(m).slice(String(prefix).length);
return `${prefix}$$${body}$$`;
}
);
// Wrap bare parenthesized chunks that look like LaTeX, e.g. (\mathbb{R}) or (x_n).
normalized = normalized.replace(
/\(([^()\n]*(?:\\[A-Za-z]+|[A-Za-z0-9]+_[A-Za-z0-9]+|[A-Za-z0-9]+\^[A-Za-z0-9]+)[^()\n]*)\)/g,
(_m, expr) => `$${expr.trim()}$`
);
// If any rule above introduced delimiters, stop here to avoid double-wrapping
// in subsequent regex passes.
if (normalized.includes('$')) {
// Repair malformed "$$(...latex...)" into "$...latex...$" for user input.
// This can appear from odd delimiter interactions in partially-normalized text.
normalized = normalized.replace(
/\$\$\((\\[A-Za-z][^)\n]*)\)/g,
(_m, expr) => `$${expr.trim()}$`
);
// Repair malformed "$(...latex...)" into "$...latex...$".
normalized = normalized.replace(
/\$\((\\[A-Za-z][^)\n]*)\)/g,
(_m, expr) => `$${expr.trim()}$`
);
const displayDelimiters = normalized.match(/\$\$/g);
if (displayDelimiters && displayDelimiters.length % 2 === 1) {
normalized = `${normalized}\n$$`;
}
return normalized;
}
// Wrap common inline commands if user forgot $ delimiters.
normalized = normalized.replace(
/\\(?:frac|dfrac|tfrac|binom|sqrt|sum|int|iint|iiint|oint|prod|lim|sup|inf|min|max|argmax|argmin|alpha|beta|gamma|delta|epsilon|varepsilon|theta|vartheta|lambda|pi|rho|sigma|mu|nu|omega|partial|nabla|cdot|times|leq|geq|neq|approx|sim|infty|forall|exists|in|notin|subset|subseteq|supset|supseteq|cup|cap|to|mapsto|left|right|sin|cos|tan|sec|csc|cot|log|ln|exp|mathbb|mathbf|mathcal|mathrm|operatorname|text|overline|underline|hat|bar|vec)(?:\s*\{[^{}]*\}){0,4}(?:\s*\^[^\s{}]+)?(?:\s*_[^\s{}]+)?/g,
(m) => `$${m}$`
);
// Fallback: wrap broader bare LaTeX segments with at least one command token.
normalized = normalized.replace(
/(^|[\s(,:;])((?:[A-Za-z0-9{}()[\]^_+\-*/=|]+\s+){0,8}\\[A-Za-z]+(?:\*?)(?:\s*\{[^{}]*\}){0,4}(?:\s+[A-Za-z0-9{}()[\]^_+\-*/=|\\]+){0,8})(?=$|[\s),.;:!?])/g,
(_m, prefix, expr) => `${prefix}$${String(expr).trim()}$`
);
// Catch bare superscript/subscript tokens like x_n, a^2, x_i^2.
normalized = normalized.replace(
/(^|[\s(,:;])([A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9{}]+|\^[A-Za-z0-9{}]+){1,2})(?=$|[\s),.;:!?])/g,
(_m, prefix, expr) => `${prefix}$${expr}$`
);
return normalized;
};
const PlotImage: React.FC<{ src?: string; alt?: string }> = ({ src, alt, ...props }) => {
const [currentSrc, setCurrentSrc] = useState<string | undefined>(src);
const [fallbackSrc, setFallbackSrc] = useState<string | undefined>(undefined);
useEffect(() => {
if (!src) {
setCurrentSrc(undefined);
setFallbackSrc(undefined);
return;
}
if (src.startsWith('data:image/')) {
try {
const [meta, data] = src.split(',', 2);
const mimeMatch = meta.match(/^data:(image\/[^;]+);base64$/);
if (mimeMatch && data) {
const byteChars = atob(data);
const byteNumbers = new Array(byteChars.length);
for (let i = 0; i < byteChars.length; i += 1) {
byteNumbers[i] = byteChars.charCodeAt(i);
}
const blob = new Blob([new Uint8Array(byteNumbers)], { type: mimeMatch[1] });
const objectUrl = URL.createObjectURL(blob);
setCurrentSrc(objectUrl);
setFallbackSrc(src);
return () => {
URL.revokeObjectURL(objectUrl);
};
}
} catch {
setCurrentSrc(src);
setFallbackSrc(undefined);
}
}
setCurrentSrc(src);
setFallbackSrc(undefined);
}, [src]);
if (!currentSrc) {
return null;
}
return (
<img
src={currentSrc}
alt={alt || 'Plot'}
style={{ maxWidth: '100%', height: 'auto', margin: '1rem 0' }}
onError={() => {
if (fallbackSrc && fallbackSrc !== currentSrc) {
setCurrentSrc(fallbackSrc);
}
}}
{...props}
/>
);
};
// ─── Per-block KaTeX rendering (memoized — never re-render once a math block completes) ───
const KatexDisplay = React.memo(function KatexDisplay({ math }: { math: string }) {
const html = useMemo(() => {
try {
return katex.renderToString(math, { throwOnError: false, strict: false, displayMode: true });
} catch {
return `<span class="katex-error">${math.replace(/&/g, '&').replace(/</g, '<')}</span>`;
}
}, [math]);
return <div className="math math-display" dangerouslySetInnerHTML={{ __html: html }} />;
});
const KatexInline = React.memo(function KatexInline({ math }: { math: string }) {
const html = useMemo(() => {
try {
return katex.renderToString(math, { throwOnError: false, strict: false });
} catch {
return `<span class="katex-error">${math.replace(/&/g, '&').replace(/</g, '<')}</span>`;
}
}, [math]);
return <span className="math math-inline" dangerouslySetInnerHTML={{ __html: html }} />;
});
type ContentSegment =
| { type: 'markdown'; content: string }
| { type: 'display'; content: string }
| { type: 'inline'; content: string };
/** Split preprocessed markdown into interleaved text and completed-math segments. */
function segmentMath(content: string): ContentSegment[] {
const segments: ContentSegment[] = [];
// Display math env names — ordered so longer names (aligned, eqnarray*) come before shorter prefixes.
const displayEnvNames = 'aligned|align\\*|align|equation\\*|equation|gather\\*|gather|multline\\*|multline|array|matrix|pmatrix|bmatrix|vmatrix|Vmatrix|cases|split|eqnarray\\*|eqnarray';
// Match (in priority order):
// 1. $$...$$ display math → group 1 = math content
// 2. \begin{env}..\end{env} → group 2 = env name, group 3 = env body (pass full m[0] to KaTeX)
// 3. $...$ inline math (no newlines) → group 4 = math content
const mathRegex = new RegExp(
'\\$\\$([\\s\\S]*?)\\$\\$(?!\\$)' +
`|\\\\begin\\{(${displayEnvNames})\\}([\\s\\S]*?)\\\\end\\{\\2\\}` +
'|\\$(?!\\$)((?:[^$\\\\\\n]|\\\\.)+?)\\$(?!\\$)',
'g'
);
let lastIndex = 0;
let m: RegExpExecArray | null;
while ((m = mathRegex.exec(content)) !== null) {
if (m.index > lastIndex) {
segments.push({ type: 'markdown', content: content.slice(lastIndex, m.index) });
}
if (m[0].startsWith('$$')) {
segments.push({ type: 'display', content: (m[1] ?? '').trim() });
} else if (m[0].startsWith('\\begin{')) {
// Bare \begin{env}...\end{env} not wrapped in $$: pass full expression to KaTeX
segments.push({ type: 'display', content: m[0].trim() });
} else {
segments.push({ type: 'inline', content: (m[4] ?? '').trim() });
}
lastIndex = m.index + m[0].length;
}
if (lastIndex < content.length) {
segments.push({ type: 'markdown', content: content.slice(lastIndex) });
}
return segments;
}
const mdOnlyComponents = {
code({ className, children, ...props }: any) {
const codeTheme = React.useContext(CodeThemeContext);
const match = /language-(\w+)/.exec(className || '');
const rawContent = String(children).replace(/\n$/, '');
// If the code block contains a LaTeX display math environment, render as KaTeX.
// This handles cases where the LLM wraps \begin{aligned} etc. in code fences.
if (/\\begin\{(?:aligned|align\*?|equation\*?|gather\*?|multline\*?|array|matrix|pmatrix|bmatrix|vmatrix|Vmatrix|cases|split|eqnarray\*?)\}/.test(rawContent)) {
return <KatexDisplay math={rawContent} />;
}
return match ? (
<SyntaxHighlighter style={codeTheme as any} language={match[1]} PreTag="div" {...props}>
{rawContent}
</SyntaxHighlighter>
) : (
<code className={className} {...props}>{children}</code>
);
},
img({ src, alt, ...props }: any) { return <PlotImage src={src} alt={alt} {...props} />; },
};
/**
* Renders content as interleaved Markdown + per-block KaTeX.
* Each completed math block renders once and is stable (memoized by content).
* Only the trailing partial-text segment re-renders on each stream chunk.
*/
const SegmentedMarkdown = React.memo(function SegmentedMarkdown({ content }: { content: string }) {
const segments = useMemo(() => segmentMath(content), [content]);
return (
<>
{segments.map((seg, i) => {
if (seg.type === 'display') {
return <KatexDisplay key={`d-${i}-${seg.content.length}`} math={seg.content} />;
}
if (seg.type === 'inline') {
return <KatexInline key={`i-${i}-${seg.content.length}`} math={seg.content} />;
}
return (
<ReactMarkdown
key={`m-${i}`}
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeRaw]}
urlTransform={allowDataImageUrl}
components={mdOnlyComponents}
>
{seg.content}
</ReactMarkdown>
);
})}
</>
);
});
interface Message {
id: string;
role: 'user' | 'assistant' | 'system';
content: string;
timestamp: Date;
toolCalls?: ToolCall[];
thinkingContent?: string; // V3 status/tool log shown in Thinking panel
thinkingExpanded?: boolean; // Whether the Thinking panel is open
reasoningContent?: string; // DeepSeek-Reasoner reasoning trace
reasoningExpanded?: boolean; // Whether the reasoning panel is open
isStreaming?: boolean;
}
interface ToolCall {
id?: string;
name: string;
input: string;
output: string;
error?: boolean; // Tool execution failed
isGenerating?: boolean; // AI is writing the code
isExecuting?: boolean; // Code is running in sandbox
}
interface User {
username: string;
name: string;
}
interface ConversationItem {
id: string;
title: string;
timestamp: Date;
messages: Message[];
}
const GATEWAY_URL = import.meta.env.VITE_GATEWAY_URL || 'https://deepthoughtai-evo-gateway.hf.space';
console.log('App Gateway URL:', GATEWAY_URL); // Debug log
// ---------------------------------------------------------------------------
// MessageItem – memoized so keystroke-driven re-renders don't re-render every
// historical message. Only the specific message that changes re-renders.
// ---------------------------------------------------------------------------
interface MessageItemProps {
message: Message;
userName: string | undefined;
onCopyMarkdown: (content: string, event: React.MouseEvent) => void;
onCopyEverything: (message: Message, event: React.MouseEvent) => void;
onToggleReasoning: (messageId: string, open: boolean) => void;
onToggleThinking: (messageId: string, open: boolean) => void;
showThinking?: boolean;
}
const MessageItem = React.memo(function MessageItem({
message,
userName,
onCopyMarkdown,
onCopyEverything,
onToggleReasoning,
onToggleThinking,
showThinking = false,
}: MessageItemProps) {
const codeTheme = React.useContext(CodeThemeContext);
if (
message.role === 'assistant' &&
!message.content &&
!message.thinkingContent &&
!message.reasoningContent &&
(!message.toolCalls || message.toolCalls.length === 0)
) {
if (!showThinking) return null;
}
return (
<div className={`message message-${message.role}`}>
<div className="message-avatar">
{message.role === 'user' ? (
<div className="avatar avatar--user">{userName?.[0]?.toUpperCase() ?? 'U'}</div>
) : (
<div className="avatar avatar--assistant">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/>
</svg>
</div>
)}
</div>
<div className="message-body">
<div className="message-meta">
<span className="message-role-label">
{message.role === 'user' ? (userName ?? 'You') : 'EVO'}
</span>
<span className="message-time">{message.timestamp.toLocaleTimeString()}</span>
{message.role === 'assistant' && (
<div className="message-actions">
<button
className="action-btn"
onClick={(e) => onCopyEverything(message, e)}
title="Copy all (with tool outputs)"
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
<circle cx="11.5" cy="11.5" r="1.5" fill="currentColor"></circle>
<circle cx="16.5" cy="11.5" r="1.5" fill="currentColor"></circle>
<circle cx="11.5" cy="16.5" r="1.5" fill="currentColor"></circle>
<circle cx="16.5" cy="16.5" r="1.5" fill="currentColor"></circle>
</svg>
</button>
<button
className="action-btn"
onClick={(e) => onCopyMarkdown(message.content, e)}
title="Copy markdown"
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
</svg>
</button>
</div>
)}
</div>
{message.content && (
<div className="message-content">
{message.role === 'assistant' && message.isStreaming ? (
(() => {
const { safe, tail } = splitStreamingContent(message.content);
return (
<>
{safe && <SegmentedMarkdown content={safe} />}
{tail && <div className="streaming-content">{tail}</div>}
</>
);
})()
) : (
<ReactMarkdown
remarkPlugins={[[remarkMath, { singleDollarTextMath: true }], remarkGfm]}
rehypePlugins={[rehypeRaw, [rehypeKatex, { throwOnError: false, strict: false }]]}
urlTransform={allowDataImageUrl}
components={{
code({ className, children, ...props }: any) {
const match = /language-(\w+)/.exec(className || '');
const rawContent = String(children).replace(/\n$/, '');
if (/\\begin\{(?:aligned|align\*?|equation\*?|gather\*?|multline\*?|array|matrix|pmatrix|bmatrix|vmatrix|Vmatrix|cases|split|eqnarray\*?)\}/.test(rawContent)) {
return <KatexDisplay math={rawContent} />;
}
return match ? (
<SyntaxHighlighter style={codeTheme as any} language={match[1]} PreTag="div" {...props}>
{rawContent}
</SyntaxHighlighter>
) : (
<code className={className} {...props}>{children}</code>
);
},
img({ src, alt, ...props }: any) { return <PlotImage src={src} alt={alt} {...props} />; },
}}
>
{message.role === 'user' ? normalizeUserLatex(message.content) : message.content}
</ReactMarkdown>
)}
</div>
)}
{showThinking && !message.content && !message.reasoningContent && !message.thinkingContent && (!message.toolCalls || message.toolCalls.length === 0) && (
<div className="typing-dots thinking-inline">
<span></span><span></span><span></span>
<em className="status-message">Thinking...</em>
</div>
)}
{message.thinkingContent && (
<details
className={`reasoning-trace thinking-trace${message.isStreaming ? ' reasoning-streaming' : ''}`}
open={message.thinkingExpanded}
onToggle={(e) => {
const open = (e.currentTarget as HTMLDetailsElement).open;
onToggleThinking(message.id, open);
}}
>
<summary className="reasoning-header">
<span>Thinking</span>
{message.isStreaming && (
<span className="reasoning-live-indicator">
<span className="reasoning-live-dot" />
<span className="reasoning-live-dot" />
<span className="reasoning-live-dot" />
</span>
)}
</summary>
<div
className="reasoning-content thinking-log"
>
{(message.thinkingContent || '').replace(/\n{3,}/g, '\n\n')}
</div>
</details>
)}
{message.reasoningContent && (
<details
className={`reasoning-trace${message.isStreaming ? ' reasoning-streaming' : ''}`}
open={message.reasoningExpanded}
onToggle={(e) => {
const open = (e.currentTarget as HTMLDetailsElement).open;
onToggleReasoning(message.id, open);
}}
>
<summary className="reasoning-header">
<span className="reasoning-icon"></span>
<span>Reasoning</span>
{message.isStreaming && (
<span className="reasoning-live-indicator">
<span className="reasoning-live-dot" />
<span className="reasoning-live-dot" />
<span className="reasoning-live-dot" />
</span>
)}
</summary>
<div
className="reasoning-content"
>
{message.reasoningContent}
</div>
</details>
)}
{message.toolCalls && message.toolCalls.length > 0 && (
<div className="tool-calls">
{message.toolCalls.map((tool, idx) => (
<details key={idx} className="tool-call">
<summary className="tool-call-header">
<span className="tool-name">{tool.name.replace(/_exec$/, '').replace(/_/g, ' ')}</span>
{tool.isGenerating && (
<span className="tool-status generating">
<span className="dot"></span><span className="dot"></span><span className="dot"></span>
<span className="status-text">Generating...</span>
</span>
)}
{tool.isExecuting && (
<span className="tool-status executing">
<span className="dot"></span><span className="dot"></span><span className="dot"></span>
<span className="status-text">Executing...</span>
</span>
)}
{tool.output && !tool.isGenerating && !tool.isExecuting && (
tool.error ? <span className="crossmark">✗</span> : <span className="checkmark">✓</span>
)}
</summary>
<div className="tool-call-content">
<details className="tool-section">
<summary className="tool-section-label">Input:</summary>
<pre className="tool-code tool-input-scroll">{tool.input}</pre>
</details>
{tool.output && (
<div className="tool-section">
<div className="tool-section-label">Output:</div>
<div className="tool-output">
<ReactMarkdown
remarkPlugins={[[remarkMath, { singleDollarTextMath: true }], remarkGfm]}
rehypePlugins={[rehypeRaw, [rehypeKatex, { throwOnError: false, strict: false }]]}
urlTransform={allowDataImageUrl}
components={{
code({ className, children, ...props }: any) {
const match = /language-(\w+)/.exec(className || '');
const rawContent = String(children).replace(/\n$/, '');
if (/\\begin\{(?:aligned|align\*?|equation\*?|gather\*?|multline\*?|array|matrix|pmatrix|bmatrix|vmatrix|Vmatrix|cases|split|eqnarray\*?)\}/.test(rawContent)) {
return <KatexDisplay math={rawContent} />;
}
return match ? (
<SyntaxHighlighter style={codeTheme as any} language={match[1]} PreTag="div" {...props}>
{rawContent}
</SyntaxHighlighter>
) : (
<code className={className} {...props}>{children}</code>
);
},
img({ src, alt, ...props }: any) { return <PlotImage src={src} alt={alt} {...props} />; },
}}
>
{tool.output}
</ReactMarkdown>
</div>
</div>
)}
</div>
</details>
))}
</div>
)}
</div>
</div>
);
});
function App() {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [user, setUser] = useState<User | null>(null);
const [sessionId, setSessionId] = useState<string | null>(null);
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [isGenerating, setIsGenerating] = useState(false);
const [responseComplete, setResponseComplete] = useState(false);
const [statusMessage, setStatusMessage] = useState('');
const [activeSymbolCategory, setActiveSymbolCategory] = useState('greek');
const [showMathSymbols, setShowMathSymbols] = useState(false);
const [webSearchEnabled, setWebSearchEnabled] = useState(true);
const [selectedModel, setSelectedModel] = useState<string>('deepseek-chat');
const [sidebarOpen, setSidebarOpen] = useState(true);
const [conversations, setConversations] = useState<ConversationItem[]>([]);
const [currentConvId, setCurrentConvId] = useState<string | null>(null);
const [theme, setTheme] = useState<'dark' | 'light'>(() => {
return (localStorage.getItem('evo_theme') as 'dark' | 'light') || 'light';
});
useEffect(() => {
document.documentElement.dataset.theme = theme;
localStorage.setItem('evo_theme', theme);
}, [theme]);
const toggleTheme = () => setTheme(t => t === 'dark' ? 'light' : 'dark');
// Memoize so CodeThemeContext.Provider doesn't re-render all consumers on every render
const codeTheme = useMemo(
() => (theme === 'dark' ? terminalTheme : lightCodeTheme),
[theme]
);
const chatPlaceholder = useMemo(
() => LOGIC_SAYINGS[Math.floor(Math.random() * LOGIC_SAYINGS.length)],
[]
);
const AVAILABLE_MODELS = [
{ id: 'deepseek-chat', label: 'DeepSeek V3', title: 'DeepSeek V3 (fast)' },
{ id: 'deepseek-reasoner', label: 'DeepSeek R1', title: 'DeepSeek R1 (deep reasoning)' },
];
const examples = [
{
label: 'Prove $\\sqrt{2}$ is irrational',
prompt: 'Prove that sqrt(2) is irrational using first principles.',
},
{
label: 'Solve integral $x^2\\sin(x)$',
prompt: 'Solve the integral of x^2 sin(x) with SymPy and show the result.',
},
{
label: 'Find primes with Prolog',
prompt: 'Find all prime numbers less than 100 using Prolog.',
},
{
label: 'Eigenvalues of $\\begin{bmatrix}2&1\\\\1&2\\end{bmatrix}$',
prompt: 'Find the eigenvalues and eigenvectors of the matrix [[2,1],[1,2]] and verify by substitution.',
},
];
const toggleModel = () => {
setSelectedModel((prev) =>
prev === 'deepseek-chat' ? 'deepseek-reasoner' : 'deepseek-chat'
);
};
const messagesContainerRef = useRef<HTMLDivElement>(null);
const abortControllerRef = useRef<AbortController | null>(null);
const requestIdRef = useRef<number>(0);
const textareaRef = useRef<HTMLTextAreaElement>(null);
// Logout on page close or refresh
useEffect(() => {
const handleBeforeUnload = () => {
if (sessionId) {
// keepalive allows the request to continue during page unload.
fetch(`${GATEWAY_URL}/api/auth/logout`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${sessionId}`,
},
body: JSON.stringify({}),
keepalive: true,
}).catch(() => {
// Best-effort logout during unload; ignore failures.
});
}
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, [sessionId]);
// Auto-save conversation when a response fully completes (not during streaming)
useEffect(() => {
if (responseComplete && !isGenerating && messages.length > 0) {
const newId = saveConversation(messages, currentConvId);
if (newId && !currentConvId) setCurrentConvId(String(newId));
}
}, [responseComplete, isGenerating, messages, currentConvId]);
const handleStopGeneration = () => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
setIsLoading(false);
setIsGenerating(false);
setStatusMessage('');
// Stop all streaming animations and tool executing states
setMessages((prev) =>
prev.map((msg) => ({
...msg,
isStreaming: false,
toolCalls: msg.toolCalls?.map((tc) =>
tc.isGenerating || tc.isExecuting
? { ...tc, isGenerating: false, isExecuting: false }
: tc
),
}))
);
};
const handleSendMessage = async () => {
if (!input.trim() || isGenerating) return;
const userMessage: Message = {
id: Date.now().toString(),
role: 'user',
content: input,
timestamp: new Date(),
};
setMessages((prev) => [...prev, userMessage]);
const currentInput = input;
setInput('');
setIsLoading(true);
setIsGenerating(true);
setResponseComplete(false);
setStatusMessage('Connecting to AI model...');
// Create a temporary assistant message that will be updated
const assistantId = (Date.now() + 1).toString();
const assistantMessage: Message = {
id: assistantId,
role: 'assistant',
content: '',
timestamp: new Date(),
toolCalls: [],
isStreaming: false,
};
setMessages((prev) => [...prev, assistantMessage]);
// Stamp this request so stale finally/catch blocks can't clobber a newer request
requestIdRef.current += 1;
const myRequestId = requestIdRef.current;
let wasAborted = false;
const isR1 = selectedModel === 'deepseek-reasoner';
try {
// Create new AbortController for this request
abortControllerRef.current = new AbortController();
const headers: HeadersInit = {
'Content-Type': 'application/json'
};
// Add Authorization header with session ID
if (sessionId) {
headers['Authorization'] = `Bearer ${sessionId}`;
}
const response = await fetch(`${GATEWAY_URL}/api/chat`, {
method: 'POST',
headers,
body: JSON.stringify({
message: currentInput,
model: selectedModel,
webSearchEnabled,
}),
signal: abortControllerRef.current.signal,
});
if (!response.ok) {
// Try to get error message from response
let errorMessage = `Backend returned an error ${response.status}`;
try {
const errorData = await response.json();
errorMessage = errorData.error || errorData.message || errorMessage;
} catch (e) {
// Response wasn't JSON, use status text
errorMessage = response.statusText || errorMessage;
}
throw new Error(errorMessage);
}
const reader = response.body?.getReader();
const decoder = new TextDecoder();
if (!reader) {
throw new Error('No response body');
}
let buffer = '';
// Local mirrors – avoid reading React state in the hot path.
let localThinkingContent = '';
let finalBuffer = '';
let toolsUsed = false;
// RAF batching for content_chunk / reasoning_chunk.
// Accumulate text locally; flush to React state at most once per frame.
let pendingThinkingFlush = '';
let pendingReasoningFlush = '';
let rafId: number | null = null;
let firstChunkSeen = false;
const updateAssistantMessage = (updater: (msg: Message) => Message) => {
setMessages((prev) => {
let idx = prev.length - 1;
while (idx >= 0 && prev[idx].id !== assistantId) idx -= 1;
if (idx < 0) return prev;
const next = prev.slice();
next[idx] = updater(prev[idx]);
return next;
});
};
const flushChunks = () => {
rafId = null;
const tc = pendingThinkingFlush;
const rc = pendingReasoningFlush;
pendingThinkingFlush = '';
pendingReasoningFlush = '';
if (!tc && !rc) return;
updateAssistantMessage((msg) => {
const next: typeof msg = { ...msg, isStreaming: true };
if (tc) {
if (isR1) {
// R1: content chunks are the final answer, not thinking — route
// directly to content so the Thinking panel never shows for R1.
next.content = (msg.content || '') + tc;
} else {
next.thinkingContent = (msg.thinkingContent || '') + tc;
next.thinkingExpanded = true;
}
}
if (rc) {
next.reasoningContent = (msg.reasoningContent || '') + rc;
next.reasoningExpanded = true;
}
return next;
});
};
const scheduleFlush = () => {
if (rafId === null) rafId = requestAnimationFrame(flushChunks);
};
while (true) {
const { done, value } = await reader.read();
if (done) {
// Cancel any pending RAF and do a final synchronous flush
if (rafId !== null) { cancelAnimationFrame(rafId); rafId = null; }
flushChunks();
setIsLoading(false);
setResponseComplete(true);
setStatusMessage('');
break;
}
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (!line.trim()) continue;
const eventMatch = line.match(/^event: (.+)$/m);
const dataMatch = line.match(/^data: (.+)$/m);
if (!eventMatch || !dataMatch) continue;
const event = eventMatch[1];
const data = JSON.parse(dataMatch[1]);
if (event === 'status') {
setStatusMessage(data.message || 'Processing...');
} else if (event === 'content_chunk') {
// For V3 only: strip leading newlines when the buffer already ends with
// a newline, to avoid consecutive blank lines in the Thinking panel.
// R1 routes content_chunks to the final answer, so we must not alter them.
let chunk: string = data.chunk;
if (!isR1 && localThinkingContent.endsWith('\n') && chunk.startsWith('\n')) {
chunk = chunk.replace(/^\n+/, '');
}
localThinkingContent += chunk;
finalBuffer += chunk;
pendingThinkingFlush += chunk;
// One-time: hide spinner on first content
if (!firstChunkSeen) {
firstChunkSeen = true;
setIsLoading(false);
setResponseComplete(true);
setStatusMessage('');
}
scheduleFlush();
} else if (event === 'reasoning_chunk') {
pendingReasoningFlush += data.chunk;
if (!firstChunkSeen) {
firstChunkSeen = true;
setIsLoading(false);
setResponseComplete(true);
setStatusMessage('');
}
scheduleFlush();
} else if (event === 'tool_start') {
// Flush before handling structural events so ordering is correct
if (rafId !== null) { cancelAnimationFrame(rafId); rafId = null; }
flushChunks();
toolsUsed = true;
finalBuffer = '';
setStatusMessage(`Generating ${data.name}...`);
updateAssistantMessage((msg) => ({
...msg,
isStreaming: true,
toolCalls: [
...(msg.toolCalls || []),
{
id: data.id,
name: data.name,
input: data.input,
output: '',
isGenerating: true,
isExecuting: false,
},
],
}));
} else if (event === 'tool_executing') {
if (rafId !== null) { cancelAnimationFrame(rafId); rafId = null; }
flushChunks();
// Tool is now executing - update status
setStatusMessage(`Executing ${data.name}...`);
updateAssistantMessage((msg) => ({
...msg,
toolCalls: (msg.toolCalls || []).map((tc) =>
tc.id === data.id
? { ...tc, isGenerating: false, isExecuting: true }
: tc
),
}));
} else if (event === 'tool_complete') {
if (rafId !== null) { cancelAnimationFrame(rafId); rafId = null; }
flushChunks();
// Reset finalBuffer: any content_chunks that arrive after this
// are candidates for the final response.
// For V3 only: add a smart newline separator (avoid double blank lines).
// R1 routes pendingThinkingFlush to final content, so leave it unchanged.
finalBuffer = '';
if (!isR1) {
if (!localThinkingContent.endsWith('\n\n')) {
const sep = localThinkingContent.endsWith('\n') ? '\n' : '\n\n';
localThinkingContent += sep;
pendingThinkingFlush += sep;
}
} else {
localThinkingContent += '\n\n';
pendingThinkingFlush += '\n\n';
}
scheduleFlush();
setStatusMessage('');
const output = data.output || '';
// Strategy: Check the LAST line for success/failure indicators
// This avoids false positives from status markers (❌ Not needed) in the middle
const lines = output.trim().split('\n');
const lastLine = lines[lines.length - 1] || '';
// Success indicators on the last line OR anywhere in full output
const hasFinalSuccess =
lastLine.includes('✅ Classification stored') ||
lastLine.includes('✅ Lean 4 code compiled successfully') ||
lastLine.includes('✅ Python code executed successfully') ||
lastLine.includes('✅ SymPy code executed successfully') ||
lastLine.includes('✅ Prolog code executed') ||
lastLine.includes('✅ Found in Mathlib') ||
/✅.*completed/i.test(lastLine) ||
lastLine.includes('✅') ||
output.includes('✅ **Compilation Successful**'); // Lean 4 success (bold markdown)
// Actual failure indicators (not status markers like "❌ Not needed")
const hasActualFailure =
output.includes('❌ BLOCKED') ||
output.includes('❌ Python execution failed') ||
output.includes('❌ SymPy execution failed') ||
output.includes('❌ Lean 4 compilation failed') ||
output.includes('❌ **Compilation Failed**') || // Lean 4 failure (bold markdown)
output.includes('❌ Compilation Failed') || // Lean 4 failure (plain)
output.includes('❌ Not found in Mathlib') ||
output.includes('Exit code: 0') === false && /Exit code: \d+/.test(output);
// Determine error state
let hasError = false;
if (hasFinalSuccess) {
hasError = false; // Explicit success on last line
} else if (hasActualFailure) {
hasError = true; // Explicit failure
} else {
// Fallback: check for Error: prefix
hasError = output.startsWith('Error:') || output.includes('\nError:');
}
updateAssistantMessage((msg) => ({
...msg,
toolCalls: (msg.toolCalls || []).map((tc) =>
tc.id === data.id
? { ...tc, output: data.output, error: hasError, isGenerating: false, isExecuting: false }
: tc
),
}));
} else if (event === 'done') {
// Flush any remaining buffered chunks synchronously before routing
if (rafId !== null) { cancelAnimationFrame(rafId); rafId = null; }
flushChunks();
// Route content correctly:
// - No tools fired → thinkingContent is actually the final response,
// move it to content and hide the Thinking panel.
// - Tools fired → everything before the first blank-line break in
// finalBuffer is preamble (LLM commentary like "The result looks
// good, let me summarise...") → append to thinkingContent.
// Everything from the first blank-line break onward is the real
// final answer → content. If finalBuffer already starts with
// structured markdown, treat the whole thing as the final answer.
setIsLoading(false);
setIsGenerating(false);
setResponseComplete(true);
setStatusMessage('');
setMessages((prev) =>
prev.map((msg) => {
if (msg.id !== assistantId) return msg;
if (!toolsUsed) {
// Pure V3 response without tools – show as normal content,
// no Thinking panel needed.
return {
...msg,
content: localThinkingContent,
thinkingContent: undefined,
thinkingExpanded: undefined,
isStreaming: false,
};
}
// R1: content chunks were already routed to msg.content during
// streaming — just clear any residual thinkingContent and stop.
if (isR1) {
return {
...msg,
thinkingContent: undefined,
thinkingExpanded: undefined,
isStreaming: false,
};
}
// V3 tools were used.
// Determine the split point inside finalBuffer.
// If finalBuffer starts with structured markdown, don't split.
const alreadyStructured = /^\s*(#{1,6} |\*\*|\d+\.\s|\-\s)/.test(finalBuffer);
const blankLineIdx = alreadyStructured ? -1 : finalBuffer.indexOf('\n\n');
const preamble = blankLineIdx !== -1 ? finalBuffer.slice(0, blankLineIdx) : '';
const answer = blankLineIdx !== -1 ? finalBuffer.slice(blankLineIdx + 2) : finalBuffer;
const thinkingBase = localThinkingContent.slice(
0,
localThinkingContent.length - finalBuffer.length
).trimEnd();
const newThinking = preamble
? (thinkingBase + '\n\n' + preamble.trimEnd())
: (thinkingBase || undefined);
return {
...msg,
content: answer,
thinkingContent: newThinking || undefined,
thinkingExpanded: !!newThinking,
isStreaming: false,
};
})
);
} else if (event === 'error') {
if (rafId !== null) { cancelAnimationFrame(rafId); rafId = null; }
// Error occurred
setIsLoading(false);
setIsGenerating(false);
setResponseComplete(true);
setStatusMessage('');
setMessages((prev) =>
prev.map((msg) =>
msg.id === assistantId
? {
...msg,
content: `Error: ${data.error}\n${data.details || ''}`,
isStreaming: false,
}
: msg
)
);
}
}
}
} catch (error) {
// Don't show error message if request was aborted (stop button)
if (error instanceof Error && error.name === 'AbortError') {
wasAborted = true;
console.log('Request aborted by user');
return;
}
// Only update state if this is still the active request
if (myRequestId !== requestIdRef.current) return;
console.error('Error sending message:', error);
setIsLoading(false);
setIsGenerating(false);
setResponseComplete(true);
setStatusMessage('');
const errorDetail = error instanceof Error ? error.message : String(error);
setMessages((prev) =>
prev.map((msg) =>
msg.id === assistantId
? {
...msg,
content: `Sorry, there was an error processing your request.\n\n**Error:** ${errorDetail}`,
isStreaming: false,
}
: msg
)
);
} finally {
// Always clean up loading state for this request — even on abort.
// handleStopGeneration schedules the same updates synchronously, but
// React state updates are async; clearing here as well guarantees the
// UI unlocks regardless of timing so the user can send a new message.
if (myRequestId === requestIdRef.current) {
setIsLoading(false);
setIsGenerating(false);
setStatusMessage('');
abortControllerRef.current = null;
if (!wasAborted) {
setResponseComplete(true);
}
}
}
};
const handleKeyPress = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSendMessage();
}
};
const insertSymbol = (symbol: string) => {
const textarea = textareaRef.current;
if (textarea) {
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const newValue = input.slice(0, start) + symbol + input.slice(end);
setInput(newValue);
setTimeout(() => {
textarea.selectionStart = textarea.selectionEnd = start + symbol.length;
textarea.focus();
}, 0);
} else {
setInput((prev) => prev + symbol);
}
};
const saveConversation = (msgs: Message[], convId: string | null) => {
if (msgs.length === 0) return;
const firstUserMsg = msgs.find(m => m.role === 'user');
const title = firstUserMsg
? firstUserMsg.content.slice(0, 60) + (firstUserMsg.content.length > 60 ? '…' : '')
: 'New conversation';
const storageKey = `evo_conversations_${user?.username}`;
setConversations(prev => {
const existing = prev.findIndex(c => c.id === convId);
const updated: ConversationItem = {
id: convId || Date.now().toString(),
title,
timestamp: new Date(),
messages: msgs,
};
const next = existing >= 0
? prev.map(c => c.id === convId ? updated : c)
: [updated, ...prev];
const limited = next.slice(0, 50);
try { localStorage.setItem(storageKey, JSON.stringify(limited)); } catch {}
return limited;
});
return convId || Date.now().toString();
};
const loadConversation = (conv: ConversationItem) => {
setMessages(conv.messages.map(m => ({ ...m, timestamp: new Date(m.timestamp) })));
setCurrentConvId(conv.id);
setInput('');
setIsLoading(false);
setResponseComplete(false);
setStatusMessage('');
setSidebarOpen(false);
};
const deleteConversation = (convId: string, e: React.MouseEvent) => {
e.stopPropagation();
const storageKey = `evo_conversations_${user?.username}`;
setConversations(prev => {
const next = prev.filter(c => c.id !== convId);
try { localStorage.setItem(storageKey, JSON.stringify(next)); } catch {}
return next;
});
if (currentConvId === convId) {
setMessages([]);
setCurrentConvId(null);
}
};
const copyAsMarkdown = useCallback((content: string, event: React.MouseEvent) => {
const btn = event.currentTarget as HTMLElement;
const svg = btn.querySelector('svg');
navigator.clipboard.writeText(content).then(() => {
// Change icon to checkmark
if (svg) {
const originalSVG = svg.innerHTML;
svg.innerHTML = '<polyline points="20 6 9 17 4 12" stroke="currentColor" stroke-width="2.5" fill="none"></polyline>';
btn.classList.add('copied');
setTimeout(() => {
svg.innerHTML = originalSVG;
btn.classList.remove('copied');
}, 2000);
}
}).catch(err => {
console.error('Failed to copy:', err);
});
}, []);
const copyEverything = useCallback((message: Message, event: React.MouseEvent) => {
const btn = event.currentTarget as HTMLElement;
const svg = btn.querySelector('svg');
let fullText = '';
// Add main message content
if (message.content) {
fullText += message.content + '\n\n';
}
// Add all tool calls with their inputs and outputs
if (message.toolCalls && message.toolCalls.length > 0) {
fullText += '=== Tool Calls ===\n\n';
message.toolCalls.forEach((tool, idx) => {
fullText += `[${idx + 1}] Tool: ${tool.name}\n`;
fullText += `Input:\n${tool.input}\n\n`;
if (tool.output) {
fullText += `Output:\n${tool.output}\n\n`;
}
fullText += '---\n\n';
});
}
navigator.clipboard.writeText(fullText.trim()).then(() => {
// Change icon to checkmark
if (svg) {
const originalSVG = svg.innerHTML;
svg.innerHTML = '<polyline points="20 6 9 17 4 12" stroke="currentColor" stroke-width="2.5" fill="none"></polyline>';
btn.classList.add('copied');
setTimeout(() => {
svg.innerHTML = originalSVG;
btn.classList.remove('copied');
}, 2000);
}
}).catch(err => {
console.error('Failed to copy:', err);
});
}, []);
const handleToggleReasoning = useCallback((messageId: string, open: boolean) => {
setMessages((prev) => prev.map((m) => m.id === messageId ? { ...m, reasoningExpanded: open } : m));
}, []);
const handleToggleThinking = useCallback((messageId: string, open: boolean) => {
setMessages((prev) => prev.map((m) => m.id === messageId ? { ...m, thinkingExpanded: open } : m));
}, []);
const handleLogin = (
sessionId: string,
userData: User
) => {
// Keep session only in memory - will be lost on refresh
if (sessionId) {
setSessionId(sessionId);
}
setUser(userData);
setIsAuthenticated(true);
// Load this user's conversation history
try {
const stored = localStorage.getItem(`evo_conversations_${userData.username}`);
if (stored) {
const parsed = JSON.parse(stored);
setConversations(parsed.map((c: any) => ({ ...c, timestamp: new Date(c.timestamp) })));
} else {
setConversations([]);
}
} catch { setConversations([]); }
};
const handleNewChat = async () => {
// Save current conversation before clearing
if (messages.length > 0) {
saveConversation(messages, currentConvId);
}
// Cancel any ongoing request
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
// Clear backend conversation history
try {
const headers: HeadersInit = {
'Content-Type': 'application/json'
};
if (sessionId) {
headers['Authorization'] = `Bearer ${sessionId}`;
}
await fetch(`${GATEWAY_URL}/api/chat/clear`, {
method: 'POST',
headers,
body: JSON.stringify({
user: user
})
});
} catch (error) {
console.error('Failed to clear chat history:', error);
}
// Clear frontend state
setMessages([]);
setCurrentConvId(null);
setInput('');
setIsLoading(false);
setResponseComplete(false);
setStatusMessage('');
};
const handleLogout = async () => {
try {
const headers: HeadersInit = {};
if (sessionId) {
headers['Authorization'] = `Bearer ${sessionId}`;
}
await fetch(`${GATEWAY_URL}/api/auth/logout`, {
method: 'POST',
headers
});
} catch (error) {
console.error('Logout failed:', error);
}
// Clear session state
setSessionId(null);
setUser(null);
setIsAuthenticated(false);
setMessages([]);
setConversations([]);
setCurrentConvId(null);
};
if (!isAuthenticated) {
return <Login onLogin={handleLogin} />;
}
return (
<CodeThemeContext.Provider value={codeTheme}>
<div className="app">
{/* Sidebar overlay (mobile) */}
{sidebarOpen && (
<div className="sidebar-overlay" onClick={() => setSidebarOpen(false)} />
)}
{/* Left sidebar */}
<aside className={`sidebar${sidebarOpen ? ' sidebar--open' : ''}`}>
<div className="sidebar-header">
<span className="sidebar-logo">evo</span>
<button className="sidebar-collapse-btn" onClick={() => setSidebarOpen(false)} title="Collapse sidebar">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M15 18l-6-6 6-6" />
</svg>
</button>
</div>
<button className="new-chat-btn" onClick={handleNewChat}>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
<line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
</svg>
New Chat
</button>
<div className="sidebar-conversations">
{conversations.length > 0 && (
<div className="sidebar-section-label">Recent</div>
)}
{conversations.map(conv => (
<div
key={conv.id}
className={`conv-item${currentConvId === conv.id ? ' conv-item--active' : ''}`}
onClick={() => loadConversation(conv)}
>
<svg className="conv-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
</svg>
<span className="conv-title">{conv.title}</span>
<button
className="conv-delete-btn"
onClick={(e) => deleteConversation(conv.id, e)}
title="Delete"
>
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
<line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
</svg>
</button>
</div>
))}
</div>
<div className="sidebar-footer">
<div className="model-selector">
<div className="model-selector-label">Model</div>
<button
className={`model-option${selectedModel === 'deepseek-chat' ? ' model-option--active' : ''}`}
onClick={() => setSelectedModel('deepseek-chat')}
>
<span className="model-dot" />
DeepSeek V3
<span className="model-tag">Fast</span>
</button>
<button
className={`model-option${selectedModel === 'deepseek-reasoner' ? ' model-option--active' : ''}`}
onClick={() => setSelectedModel('deepseek-reasoner')}
>
<span className="model-dot model-dot--r1" />
DeepSeek R1
<span className="model-tag model-tag--r1">Reason</span>
</button>
</div>
<button className="theme-toggle-btn" onClick={toggleTheme} title="Toggle theme">
{theme === 'dark' ? (
<>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<circle cx="12" cy="12" r="5" />
<line x1="12" y1="1" x2="12" y2="3" /><line x1="12" y1="21" x2="12" y2="23" />
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64" /><line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />
<line x1="1" y1="12" x2="3" y2="12" /><line x1="21" y1="12" x2="23" y2="12" />
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36" /><line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
</svg>
Light mode
</>
) : (
<>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
</svg>
Dark mode
</>
)}
</button>
<div className="user-section">
<div className="user-avatar">{user?.name?.[0]?.toUpperCase() ?? '?'}</div>
<span className="user-name">{user?.name}</span>
<button className="user-logout-btn" onClick={handleLogout} title="Sign out">
<svg width="16" height="16" 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>
</div>
</aside>
{/* Main content */}
<main className={`main${sidebarOpen ? ' main--sidebar-open' : ''}`}>
{/* Top bar */}
<div className="topbar">
<button className="topbar-menu-btn" onClick={() => setSidebarOpen(s => !s)} title="Toggle sidebar">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<line x1="3" y1="12" x2="21" y2="12" /><line x1="3" y1="6" x2="21" y2="6" /><line x1="3" y1="18" x2="21" y2="18" />
</svg>
</button>
{!sidebarOpen && <span className="topbar-logo">evo</span>}
<div className="topbar-spacer" />
<button className="topbar-new-btn" onClick={handleNewChat}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
<line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
</svg>
New chat
</button>
</div>
{/* Messages */}
<div className="messages" ref={messagesContainerRef}>
{messages.length === 0 ? (
<div className="welcome">
<div className="welcome-logo">evo</div>
<h2 className="welcome-heading">
Logical AI
</h2>
<p className="welcome-sub">Explicit-assumption · Verification · Orchestrator</p>
<div className="examples">
{examples.map((example) => (
<button key={example.label} className="example-btn" onClick={() => setInput(example.prompt)}>
<ReactMarkdown
remarkPlugins={[remarkMath]}
rehypePlugins={[[rehypeKatex, { throwOnError: false, strict: false }]]}
components={{
p: ({ children }) => <span>{children}</span>,
}}
>
{example.label}
</ReactMarkdown>
</button>
))}
</div>
</div>
) : (
messages.map((message, index) => (
<MessageItem
key={message.id}
message={message}
userName={user?.name}
onCopyMarkdown={copyAsMarkdown}
onCopyEverything={copyEverything}
onToggleReasoning={handleToggleReasoning}
onToggleThinking={handleToggleThinking}
showThinking={isLoading && !responseComplete && message.role === 'assistant' && index === messages.length - 1}
/>
))
)}
{isLoading && !responseComplete && messages[messages.length - 1]?.role !== 'assistant' && (
<div className="typing-indicator">
<div className="avatar avatar--assistant">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/>
</svg>
</div>
<div className="typing-dots">
<span></span><span></span><span></span>
<em className="status-message">{statusMessage || 'Thinking...'}</em>
</div>
</div>
)}
</div>
{/* Input area */}
<div className="input-wrapper">
{/* Math symbols popup */}
{showMathSymbols && (
<div className="math-symbols-popup">
<div className="math-symbols-popup-content">
<div className="math-symbols-popup-header">
<span>Math Symbols</span>
<button className="math-symbols-close-btn" onClick={() => setShowMathSymbols(false)} aria-label="Close">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line>
</svg>
</button>
</div>
<div className="math-symbols">
<div className="symbol-tabs">
{['greek','operators','relations','sets','logic','arrows','special','calculus','linear','equations','matrices'].map(cat => (
<button key={cat} onClick={() => setActiveSymbolCategory(cat)} className={`symbol-tab${activeSymbolCategory === cat ? ' active' : ''}`}>
{cat.charAt(0).toUpperCase() + cat.slice(1)}
</button>
))}
</div>
<div className="symbol-content">
{activeSymbolCategory === 'greek' && (
<div className="symbol-category">
<div className="symbol-row">
{[['\\alpha ','α'],['\\beta ','β'],['\\gamma ','γ'],['\\delta ','δ'],['\\epsilon ','ε'],['\\theta ','θ'],['\\lambda ','λ'],['\\mu ','μ'],['\\pi ','π'],['\\sigma ','σ'],['\\phi ','φ'],['\\omega ','ω']].map(([s,l]) => (
<button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
))}
</div>
<div className="symbol-row">
{[['\\Gamma ','Γ'],['\\Delta ','Δ'],['\\Theta ','Θ'],['\\Lambda ','Λ'],['\\Pi ','Π'],['\\Sigma ','Σ'],['\\Phi ','Φ'],['\\Omega ','Ω']].map(([s,l]) => (
<button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
))}
</div>
</div>
)}
{activeSymbolCategory === 'operators' && (
<div className="symbol-category"><div className="symbol-row">
{[['\\sum ','∑'],['\\prod ','∏'],['\\int ','∫'],['\\iint ','∬'],['\\oint ','∮'],['\\partial ','∂'],['\\nabla ','∇'],['\\sqrt{} ','√'],['\\pm ','±'],['\\mp ','∓'],['\\times ','×'],['\\div ','÷'],['\\cdot ','·'],['\\ast ','∗']].map(([s,l]) => (
<button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
))}
</div></div>
)}
{activeSymbolCategory === 'relations' && (
<div className="symbol-category"><div className="symbol-row">
{[['\\leq ','≤'],['\\geq ','≥'],['\\neq ','≠'],['\\approx ','≈'],['\\equiv ','≡'],['\\sim ','∼'],['\\simeq ','≃'],['\\cong ','≅'],['\\propto ','∝'],['\\ll ','≪'],['\\gg ','≫']].map(([s,l]) => (
<button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
))}
</div></div>
)}
{activeSymbolCategory === 'sets' && (
<div className="symbol-category"><div className="symbol-row">
{[['\\in ','∈'],['\\notin ','∉'],['\\subset ','⊂'],['\\subseteq ','⊆'],['\\supset ','⊃'],['\\supseteq ','⊇'],['\\cup ','∪'],['\\cap ','∩'],['\\emptyset ','∅'],['\\setminus ','\\']].map(([s,l]) => (
<button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
))}
</div></div>
)}
{activeSymbolCategory === 'logic' && (
<div className="symbol-category"><div className="symbol-row">
{[['\\forall ','∀'],['\\exists ','∃'],['\\nexists ','∄'],['\\land ','∧'],['\\lor ','∨'],['\\neg ','¬'],['\\implies ','⟹'],['\\iff ','⟺'],['\\vdash ','⊢'],['\\models ','⊨']].map(([s,l]) => (
<button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
))}
</div></div>
)}
{activeSymbolCategory === 'arrows' && (
<div className="symbol-category"><div className="symbol-row">
{[['\\to ','→'],['\\leftarrow ','←'],['\\leftrightarrow ','↔'],['\\Rightarrow ','⇒'],['\\Leftarrow ','⇐'],['\\Leftrightarrow ','⇔'],['\\mapsto ','↦'],['\\uparrow ','↑'],['\\downarrow ','↓']].map(([s,l]) => (
<button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
))}
</div></div>
)}
{activeSymbolCategory === 'special' && (
<div className="symbol-category">
<div className="symbol-row">
{[['\\mathbb{R} ','ℝ'],['\\mathbb{C} ','ℂ'],['\\mathbb{N} ','ℕ'],['\\mathbb{Z} ','ℤ'],['\\mathbb{Q} ','ℚ'],['\\infty ','∞'],['\\aleph ','ℵ'],['\\hbar ','ℏ'],['\\ell ','ℓ']].map(([s,l]) => (
<button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
))}
</div>
<div className="symbol-row">
{[['\\langle \\rangle ','⟨⟩'],['\\lfloor \\rfloor ','⌊⌋'],['\\lceil \\rceil ','⌈⌉'],['\\{ \\} ','{}'],['\\lVert \\rVert ','‖‖']].map(([s,l]) => (
<button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
))}
</div>
</div>
)}
{activeSymbolCategory === 'calculus' && (
<div className="symbol-category"><div className="symbol-row">
{[['\\lim ','lim'],['\\sup ','sup'],['\\inf ','inf'],['\\max ','max'],['\\min ','min'],['\\frac{}{} ','a/b'],['^{} ','xⁿ'],['_{} ','xₙ']].map(([s,l]) => (
<button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
))}
</div></div>
)}
{activeSymbolCategory === 'linear' && (
<div className="symbol-category"><div className="symbol-row">
{[['\\oplus ','⊕'],['\\otimes ','⊗'],['\\odot ','⊙'],['\\circ ','∘'],['\\perp ','⊥'],['\\parallel ','∥'],['\\det ','det'],['\\dim ','dim']].map(([s,l]) => (
<button key={s} onClick={() => insertSymbol(s)} className="symbol-btn" title={s.trim()}>{l}</button>
))}
</div></div>
)}
{activeSymbolCategory === 'equations' && (
<div className="symbol-category">
<div className="symbol-row">
<button onClick={() => insertSymbol('$ $')} className="symbol-btn template-btn" title="Inline math">$...$</button>
<button onClick={() => insertSymbol('$$\n \n$$')} className="symbol-btn template-btn" title="Display math">$$...$$</button>
<button onClick={() => insertSymbol('\\begin{align}\n & = \\\\\n & = \n\\end{align}')} className="symbol-btn template-btn">align</button>
<button onClick={() => insertSymbol('\\begin{cases}\n & \\text{if } \\\\\n & \\text{if } \n\\end{cases}')} className="symbol-btn template-btn">cases</button>
<button onClick={() => insertSymbol('\\begin{equation}\n \n\\end{equation}')} className="symbol-btn template-btn">equation</button>
<button onClick={() => insertSymbol('\\begin{aligned}\n & \\\\\n & \n\\end{aligned}')} className="symbol-btn template-btn">aligned</button>
</div>
<div className="symbol-row">
<button onClick={() => insertSymbol('\\begin{cases}\n a_1x + b_1y = c_1 \\\\\n a_2x + b_2y = c_2\n\\end{cases}')} className="symbol-btn template-btn">2 eq</button>
<button onClick={() => insertSymbol('\\begin{cases}\n a_1x + b_1y + c_1z = d_1 \\\\\n a_2x + b_2y + c_2z = d_2 \\\\\n a_3x + b_3y + c_3z = d_3\n\\end{cases}')} className="symbol-btn template-btn">3 eq</button>
</div>
</div>
)}
{activeSymbolCategory === 'matrices' && (
<div className="symbol-category">
<div className="symbol-row">
<button onClick={() => insertSymbol('\\begin{pmatrix}\n a & b \\\\\n c & d\n\\end{pmatrix}')} className="symbol-btn template-btn">(2×2)</button>
<button onClick={() => insertSymbol('\\begin{bmatrix}\n a & b \\\\\n c & d\n\\end{bmatrix}')} className="symbol-btn template-btn">[2×2]</button>
<button onClick={() => insertSymbol('\\begin{vmatrix}\n a & b \\\\\n c & d\n\\end{vmatrix}')} className="symbol-btn template-btn">|2×2|</button>
<button onClick={() => insertSymbol('\\begin{pmatrix}\n a & b & c \\\\\n d & e & f \\\\\n g & h & i\n\\end{pmatrix}')} className="symbol-btn template-btn">(3×3)</button>
<button onClick={() => insertSymbol('\\begin{pmatrix}\n x_1 \\\\\n x_2 \\\\\n x_3\n\\end{pmatrix}')} className="symbol-btn template-btn">col vec</button>
<button onClick={() => insertSymbol('\\begin{pmatrix} x_1 & x_2 & x_3 \\end{pmatrix}')} className="symbol-btn template-btn">row vec</button>
</div>
</div>
)}
</div>
</div>
</div>
</div>
)}
<div className="input-box">
<textarea
ref={textareaRef}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyPress}
placeholder={chatPlaceholder}
rows={3}
disabled={isGenerating}
/>
<div className="input-actions">
<button
onClick={() => setWebSearchEnabled(v => !v)}
className={`action-icon-btn${webSearchEnabled ? ' action-icon-btn--active' : ''}`}
title={webSearchEnabled ? 'Web search enabled (click to disable)' : 'Web search disabled (click to enable)'}
>
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<circle cx="12" cy="12" r="10"/>
<line x1="2" y1="12" x2="22" y2="12"/>
<path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
</svg>
</button>
<button
onClick={() => setShowMathSymbols(!showMathSymbols)}
className={`action-icon-btn${showMathSymbols ? ' action-icon-btn--active' : ''}`}
title="Math Symbols"
>
Σ
</button>
<button
onClick={toggleModel}
className={`model-toggle-btn${selectedModel === 'deepseek-reasoner' ? ' model-toggle-btn--r1' : ''}`}
title={AVAILABLE_MODELS.find(m => m.id === selectedModel)?.title}
disabled={isGenerating}
>
{selectedModel === 'deepseek-chat' ? 'V3' : 'R1'}
</button>
{isGenerating ? (
<button
onClick={handleStopGeneration}
className="stop-btn"
title="Stop generation"
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
<rect x="4" y="4" width="16" height="16" rx="2"/>
</svg>
</button>
) : (
<button
onClick={handleSendMessage}
disabled={!input.trim()}
className="send-btn"
title="Send (Enter)"
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
</button>
)}
</div>
</div>
<div className="input-footer">Press Enter to send · Shift+Enter for new line</div>
</div>
</main>
</div>
</CodeThemeContext.Provider>
);
}
export default App;
import React, { useState, useRef, useEffect, useMemo, useCallback } from 'react';
import ReactMarkdown, { defaultUrlTransform } from 'react-markdown';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import remarkMath from 'remark-math';
import remarkGfm from 'remark-gfm';
import rehypeKatex from 'rehype-katex';
import rehypeRaw from 'rehype-raw';
import 'katex/dist/katex.min.css';
import katex from 'katex';
import Login from './Login';
import './App.css';
const LOGIC_SAYINGS = [
"Logic is disciplined honesty",
"Logic tames intuition",
"Logic survives scrutiny",
"Logic resists wishful thinking",
"Logic clarifies chaos",
"Logic enforces consistency",
"Logic demands consequences",
"Logic hates contradiction",
"Logic respects structure",
"Logic questions assumptions",
"Logic over loud opinions",
"Logic scales beyond intuition",
"Logic is structured doubt",
"Logic follows necessity",
"Logic earns trust",
"Logic trims nonsense",
"Logic values implication",
"Logic prevents self-deception",
"Logic is careful thinking",
"Logic disciplines belief",
"Logic outlives emotion",
"Logic defines fairness",
"Logic reveals errors",
"Logic needs no applause",
"Logic is patient clarity",
"Logic refuses shortcuts",
"Logic enforces coherence",
"Logic invites verification",
"Logic keeps promises",
"Logic respects evidence",
"Logic cuts cleanly",
"Logic exposes contradictions",
"Logic is structured reasoning",
"Logic defeats ambiguity",
"Logic rejects special pleading",
"Logic anchors truth",
"Logic strengthens arguments",
"Logic filters belief",
"Logic withstands pressure",
"Logic enables understanding",
"Logic is mental hygiene",
"Logic values consistency",
"Logic guards intelligence",
"Logic is intellectual integrity",
"Logic reveals necessity",
"Logic is consequence-aware",
"Logic clarifies premises",
"Logic enforces discipline",
"Logic refines thought",
"Logic avoids contradiction",
"Logic resists manipulation",
"Logic empowers truth",
"Logic disciplines intuition",
"Logic respects implication",
"Logic is rigorous thinking",
"Logic survives opposition",
"Logic rejects ambiguity",
"Logic is systematic clarity",
"Logic curbs bias",
"Logic anchors reasoning",
"Logic exposes fallacies",
"Logic enforces structure",
"Logic is formal honesty",
"Logic strengthens insight",
"Logic trims assumptions",
"Logic invites challenge",
"Logic prefers coherence",
"Logic defeats confusion",
"Logic remains impartial",
"Logic respects consequences",
"Logic makes sense durable",
"Logic tests belief",
"Logic values precision",
"Logic demands justification",
"Logic refines arguments",
"Logic guards truth",
"Logic stabilizes thought",
"Logic is disciplined skepticism",
"Logic clarifies meaning",
"Logic enforces necessity",
"Logic rejects contradictions",
"Logic sustains reasoning",
"Logic keeps ideas honest",
"Logic enforces fairness",
"Logic structures understanding",
"Logic prevents nonsense",