fraudTech commited on
Commit
cfa14d5
·
verified ·
1 Parent(s): fdb3241

no mathjax

Browse files
Files changed (1) hide show
  1. web/src/App.tsx +238 -245
web/src/App.tsx CHANGED
@@ -1,15 +1,12 @@
1
  import React, { useState, useRef, useEffect, useMemo } from 'react';
2
  import ReactMarkdown from 'react-markdown';
3
  import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
 
4
  import remarkGfm from 'remark-gfm';
5
- import { MathJaxContext, MathJax } from 'better-react-mathjax';
 
6
  import Login from './Login';
7
  import './App.css';
8
- import {
9
- mathJaxConfig,
10
- preprocessMathContent,
11
- hasMathContent
12
- } from './mathjax-config';
13
 
14
 
15
  const LOGIC_SAYINGS = [
@@ -115,7 +112,12 @@ const LOGIC_SAYINGS = [
115
  "Logic enforces rationality",
116
  ];
117
 
118
-
 
 
 
 
 
119
 
120
  // Eye-health optimized warm syntax highlighting theme
121
  const terminalTheme = {
@@ -178,7 +180,7 @@ interface Message {
178
  content: string;
179
  timestamp: Date;
180
  toolCalls?: ToolCall[];
181
- thinkingContent?: string;
182
  }
183
 
184
  interface ToolCall {
@@ -186,9 +188,9 @@ interface ToolCall {
186
  name: string;
187
  input: string;
188
  output: string;
189
- error?: boolean;
190
- isGenerating?: boolean;
191
- isExecuting?: boolean;
192
  }
193
 
194
  interface User {
@@ -197,62 +199,7 @@ interface User {
197
  }
198
 
199
  const GATEWAY_URL = import.meta.env.VITE_GATEWAY_URL || 'https://deepthoughtai-evo-gateway.hf.space';
200
- console.log('App Gateway URL:', GATEWAY_URL);
201
-
202
- /**
203
- * Component to render markdown with MathJax typesetting
204
- * Renders markdown first, then MathJax typesets math expressions
205
- */
206
- const MathContent: React.FC<{ content: string }> = ({ content }) => {
207
- const processed = preprocessMathContent(content);
208
-
209
- return (
210
- <MathJax dynamic>
211
- <ReactMarkdown
212
- remarkPlugins={[remarkGfm]}
213
- components={{
214
- code({ className, children, ...props }: any) {
215
- const match = /language-(\w+)/.exec(className || '');
216
- return match ? (
217
- <SyntaxHighlighter
218
- style={terminalTheme as any}
219
- language={match[1]}
220
- PreTag="div"
221
- {...props}
222
- >
223
- {String(children).replace(/\n$/, '')}
224
- </SyntaxHighlighter>
225
- ) : (
226
- <code className={className} {...props}>
227
- {children}
228
- </code>
229
- );
230
- }
231
- }}
232
- >
233
- {processed}
234
- </ReactMarkdown>
235
- </MathJax>
236
- );
237
- };
238
-
239
- /**
240
- * Math Preview Component for User Input
241
- */
242
- const MathPreview: React.FC<{ content: string }> = ({ content }) => {
243
- const hasMath = hasMathContent(content);
244
-
245
- if (!hasMath) return null;
246
-
247
- return (
248
- <div className="math-preview">
249
- <div className="math-preview-label">Math Preview</div>
250
- <div className="math-preview-content">
251
- <MathContent content={content} />
252
- </div>
253
- </div>
254
- );
255
- };
256
 
257
  function App() {
258
  const [isAuthenticated, setIsAuthenticated] = useState(false);
@@ -263,16 +210,17 @@ function App() {
263
  const [isLoading, setIsLoading] = useState(false);
264
  const [responseComplete, setResponseComplete] = useState(false);
265
  const [statusMessage, setStatusMessage] = useState('');
266
- const showMathPreview = true;
267
  const messagesEndRef = useRef<HTMLDivElement>(null);
268
  const messagesContainerRef = useRef<HTMLDivElement>(null);
269
  const abortControllerRef = useRef<AbortController | null>(null);
270
 
 
271
  const randomSaying = useMemo(
272
  () => LOGIC_SAYINGS[Math.floor(Math.random() * LOGIC_SAYINGS.length)],
273
  []
274
  );
275
 
 
276
  useEffect(() => {
277
  const verifyAuth = async () => {
278
  try {
@@ -286,18 +234,11 @@ function App() {
286
  });
287
 
288
  if (response.ok) {
289
- // Check if response has content before parsing
290
- const text = await response.text();
291
- if (text) {
292
- const data = JSON.parse(text);
293
- setUser(data.user);
294
- setIsAuthenticated(true);
295
- } else {
296
- console.warn('Empty response from auth verification');
297
- localStorage.removeItem('session_id');
298
- setSessionId(null);
299
- }
300
  } else {
 
301
  localStorage.removeItem('session_id');
302
  setSessionId(null);
303
  }
@@ -312,10 +253,12 @@ function App() {
312
  }, [sessionId]);
313
 
314
  useEffect(() => {
 
315
  const container = messagesContainerRef.current;
316
  if (container) {
317
  const isNearBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 100;
318
  if (isNearBottom) {
 
319
  requestAnimationFrame(() => {
320
  messagesEndRef.current?.scrollIntoView({ behavior: 'smooth', block: 'end' });
321
  });
@@ -340,6 +283,7 @@ function App() {
340
  setResponseComplete(false);
341
  setStatusMessage('Connecting to AI model...');
342
 
 
343
  const assistantId = (Date.now() + 1).toString();
344
  const assistantMessage: Message = {
345
  id: assistantId,
@@ -352,12 +296,14 @@ function App() {
352
  setMessages((prev) => [...prev, assistantMessage]);
353
 
354
  try {
 
355
  abortControllerRef.current = new AbortController();
356
 
357
  const headers: HeadersInit = {
358
  'Content-Type': 'application/json'
359
  };
360
 
 
361
  if (sessionId) {
362
  headers['Authorization'] = `Bearer ${sessionId}`;
363
  }
@@ -367,6 +313,7 @@ function App() {
367
  headers,
368
  body: JSON.stringify({
369
  message: currentInput
 
370
  }),
371
  signal: abortControllerRef.current.signal,
372
  });
@@ -388,6 +335,7 @@ function App() {
388
  const { done, value } = await reader.read();
389
 
390
  if (done) {
 
391
  setIsLoading(false);
392
  setResponseComplete(true);
393
  setStatusMessage('');
@@ -410,8 +358,11 @@ function App() {
410
  const data = JSON.parse(dataMatch[1]);
411
 
412
  if (event === 'status') {
 
413
  setStatusMessage(data.message || 'Processing...');
414
  } else if (event === 'content_chunk') {
 
 
415
  setIsLoading(false);
416
  setResponseComplete(true);
417
  setStatusMessage('');
@@ -420,6 +371,7 @@ function App() {
420
  prev.map((msg) => {
421
  if (msg.id !== assistantId) return msg;
422
 
 
423
  return {
424
  ...msg,
425
  content: (msg.content || '') + data.chunk,
@@ -427,6 +379,7 @@ function App() {
427
  })
428
  );
429
  } else if (event === 'tool_start') {
 
430
  setStatusMessage(`Generating ${data.name}...`);
431
  setMessages((prev) =>
432
  prev.map((msg) =>
@@ -449,6 +402,7 @@ function App() {
449
  )
450
  );
451
  } else if (event === 'tool_executing') {
 
452
  setStatusMessage(`Executing ${data.name}...`);
453
  setMessages((prev) =>
454
  prev.map((msg) =>
@@ -465,12 +419,16 @@ function App() {
465
  )
466
  );
467
  } else if (event === 'tool_complete') {
 
468
  setStatusMessage('');
469
  const output = data.output || '';
470
 
 
 
471
  const lines = output.trim().split('\n');
472
  const lastLine = lines[lines.length - 1] || '';
473
 
 
474
  const hasFinalSuccess =
475
  lastLine.includes('✅ Classification stored') ||
476
  lastLine.includes('✅ Lean 4 code compiled successfully') ||
@@ -481,6 +439,7 @@ function App() {
481
  /✅.*completed/i.test(lastLine) ||
482
  lastLine.includes('✅');
483
 
 
484
  const hasActualFailure =
485
  output.includes('❌ BLOCKED') ||
486
  output.includes('❌ Python execution failed') ||
@@ -489,12 +448,14 @@ function App() {
489
  output.includes('❌ Not found in Mathlib') ||
490
  output.includes('Exit code: 0') === false && /Exit code: \d+/.test(output);
491
 
 
492
  let hasError = false;
493
  if (hasFinalSuccess) {
494
- hasError = false;
495
  } else if (hasActualFailure) {
496
- hasError = true;
497
  } else {
 
498
  hasError = output.startsWith('Error:') || output.includes('\nError:');
499
  }
500
 
@@ -513,10 +474,12 @@ function App() {
513
  )
514
  );
515
  } else if (event === 'done') {
 
516
  setIsLoading(false);
517
  setResponseComplete(true);
518
  setStatusMessage('');
519
  } else if (event === 'error') {
 
520
  setIsLoading(false);
521
  setResponseComplete(true);
522
  setStatusMessage('');
@@ -534,6 +497,7 @@ function App() {
534
  }
535
  }
536
  } catch (error) {
 
537
  if (error instanceof Error && error.name === 'AbortError') {
538
  console.log('Request aborted by user');
539
  return;
@@ -554,6 +518,7 @@ function App() {
554
  )
555
  );
556
  } finally {
 
557
  setIsLoading(false);
558
  setResponseComplete(true);
559
  setStatusMessage('');
@@ -573,6 +538,7 @@ function App() {
573
  const svg = btn.querySelector('svg');
574
 
575
  navigator.clipboard.writeText(content).then(() => {
 
576
  if (svg) {
577
  const originalSVG = svg.innerHTML;
578
  svg.innerHTML = '<polyline points="20 6 9 17 4 12" stroke="currentColor" stroke-width="2.5" fill="none"></polyline>';
@@ -594,10 +560,12 @@ function App() {
594
 
595
  let fullText = '';
596
 
 
597
  if (message.content) {
598
  fullText += message.content + '\n\n';
599
  }
600
 
 
601
  if (message.toolCalls && message.toolCalls.length > 0) {
602
  fullText += '=== Tool Calls ===\n\n';
603
  message.toolCalls.forEach((tool, idx) => {
@@ -611,6 +579,7 @@ function App() {
611
  }
612
 
613
  navigator.clipboard.writeText(fullText.trim()).then(() => {
 
614
  if (svg) {
615
  const originalSVG = svg.innerHTML;
616
  svg.innerHTML = '<polyline points="20 6 9 17 4 12" stroke="currentColor" stroke-width="2.5" fill="none"></polyline>';
@@ -627,6 +596,7 @@ function App() {
627
  };
628
 
629
  const handleLogin = (sessionId: string, userData: User) => {
 
630
  if (sessionId) {
631
  localStorage.setItem('session_id', sessionId);
632
  setSessionId(sessionId);
@@ -636,11 +606,13 @@ function App() {
636
  };
637
 
638
  const handleNewChat = async () => {
 
639
  if (abortControllerRef.current) {
640
  abortControllerRef.current.abort();
641
  abortControllerRef.current = null;
642
  }
643
 
 
644
  try {
645
  const headers: HeadersInit = {
646
  'Content-Type': 'application/json'
@@ -660,6 +632,7 @@ function App() {
660
  console.error('Failed to clear chat history:', error);
661
  }
662
 
 
663
  setMessages([]);
664
  setInput('');
665
  setIsLoading(false);
@@ -682,6 +655,7 @@ function App() {
682
  console.error('Logout failed:', error);
683
  }
684
 
 
685
  localStorage.removeItem('session_id');
686
  setSessionId(null);
687
  setUser(null);
@@ -694,185 +668,204 @@ function App() {
694
  }
695
 
696
  return (
697
- <MathJaxContext
698
- config={mathJaxConfig}
699
- src="https://cdn.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-svg.min.js"
700
- >
701
- <div className="app">
702
- <header className="header">
703
- <div className="header-left">
704
- <h1 className="logo-text">evo</h1>
705
- <span className="version">v1.0</span>
706
- </div>
707
- <div className="header-right">
708
- <button
709
- className="new-chat-btn"
710
- onClick={handleNewChat}
711
- style={{ marginRight: '1rem' }}
712
- >
713
- New Chat
714
- </button>
715
- <span className="user-info">👤 {user?.name}</span>
716
- <button className="logout-btn" onClick={handleLogout}>
717
- Logout
718
- </button>
719
- </div>
720
- </header>
721
- <div className="chat-container">
722
- <div className="messages" ref={messagesContainerRef}>
723
- {messages.length === 0 && (
724
- <div className="welcome">
725
- <div className="examples">
726
- <h3>Try these examples:</h3>
727
- <button onClick={() => setInput("What is the derivative of x^2 + 1?")} className="example-btn">
728
- Calculate derivative
729
- </button>
730
- <button onClick={() => setInput("How many Rs in strawberry")} className="example-btn">
731
- Count characters
732
- </button>
733
- <button onClick={() => setInput("Prove derivative of x^2 is 2x")} className="example-btn">
734
- Prove a theorem
735
- </button>
736
- <button onClick={() => setInput("9.9 and 9.11 which is bigger?")} className="example-btn">
737
- Compare decimals
738
- </button>
739
- <button onClick={() => setInput("What is a Large Language Model?")} className="example-btn">
740
- General question
741
- </button>
742
- </div>
743
  </div>
744
- )}
745
- {messages.map((message) => {
746
- if (message.role === 'assistant' && !message.content && (!message.toolCalls || message.toolCalls.length === 0)) {
747
- return null;
748
- }
749
-
750
- return (
751
- <div key={message.id} className={`message message-${message.role}`}>
752
- <div className="message-header">
753
- <span className="message-role">
754
- {message.role === 'user' ? 'You' : 'Assistant'}
755
- </span>
756
- <div className="message-header-right">
757
- {message.role === 'assistant' && (
758
- <button
759
- className="copy-markdown-btn"
760
- onClick={(e) => copyEverything(message, e)}
761
- title="Copy everything (including expanders)"
762
- >
763
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
764
- <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
765
- <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
766
- <circle cx="11.5" cy="11.5" r="1.5" fill="currentColor"></circle>
767
- <circle cx="16.5" cy="11.5" r="1.5" fill="currentColor"></circle>
768
- <circle cx="11.5" cy="16.5" r="1.5" fill="currentColor"></circle>
769
- <circle cx="16.5" cy="16.5" r="1.5" fill="currentColor"></circle>
770
- </svg>
771
- </button>
772
- )}
773
  <button
774
  className="copy-markdown-btn"
775
- onClick={(e) => copyAsMarkdown(message.content, e)}
776
- title="Copy as markdown"
777
  >
778
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
779
  <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
780
  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
 
 
 
 
781
  </svg>
782
  </button>
783
- <span className="message-time">
784
- {message.timestamp.toLocaleTimeString()}
785
- </span>
786
- </div>
 
 
 
 
 
 
 
 
 
 
787
  </div>
788
- {/* Message content with MathJax */}
789
- {message.content && (
790
- <div className="message-content">
791
- <MathContent content={message.content} />
792
- </div>
793
- )}
794
- {/* Tool calls */}
795
- {message.toolCalls && message.toolCalls.length > 0 && (
796
- <div className="tool-calls">
797
- {message.toolCalls.map((tool, idx) => (
798
- <details key={idx} className="tool-call">
799
- <summary className="tool-call-header">
800
- <span className="tool-name">{tool.name}</span>
801
- {tool.isGenerating && (
802
- <span className="tool-status generating">
803
- <span className="dot"></span>
804
- <span className="dot"></span>
805
- <span className="dot"></span>
806
- <span className="status-text">Generating...</span>
807
- </span>
808
- )}
809
- {tool.isExecuting && (
810
- <span className="tool-status executing">
811
- <span className="dot"></span>
812
- <span className="dot"></span>
813
- <span className="dot"></span>
814
- <span className="status-text">Executing...</span>
815
- </span>
816
- )}
817
- {tool.output && !tool.isGenerating && !tool.isExecuting && (
818
- tool.error ? (
819
- <span className="crossmark">✗</span>
820
- ) : (
821
- <span className="checkmark">✓</span>
822
- )
823
- )}
824
- </summary>
825
- <div className="tool-call-content">
826
- <details className="tool-section">
827
- <summary className="tool-section-label">Input:</summary>
828
- <pre className="tool-code tool-input-scroll">{tool.input}</pre>
829
- </details>
830
- {tool.output && (
831
- <div className="tool-section">
832
- <div className="tool-section-label">Output:</div>
833
- <pre className="tool-output">{tool.output}</pre>
834
- </div>
835
- )}
836
- </div>
837
- </details>
838
- ))}
839
- </div>
840
- )}
841
- </div>
842
- );
843
- })}
844
- {isLoading && !responseComplete && (
845
- <div className="typing-indicator">
846
- <span></span>
847
- <span></span>
848
- <span></span>
849
- <em className="status-message">{statusMessage || 'Thinking...'}</em>
850
  </div>
851
- )}
852
- <div ref={messagesEndRef} />
853
- </div>
854
- <div className="input-container">
855
- <div className="input-wrapper">
856
- <textarea
857
- value={input}
858
- onChange={(e) => setInput(e.target.value)}
859
- onKeyPress={handleKeyPress}
860
- placeholder={`${randomSaying} (Shift+Enter for new line)`}
861
- disabled={isLoading}
862
- rows={3}
863
- />
864
- {showMathPreview && input && (
865
- <MathPreview content={input} />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
866
  )}
867
  </div>
868
- <button onClick={handleSendMessage} disabled={isLoading || !input.trim()} className="send-btn">
869
- {isLoading ? 'Sending...' : 'Send'}
870
- </button>
871
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
872
  </div>
873
  </div>
874
- </MathJaxContext>
875
  );
876
  }
877
 
878
- export default App;
 
1
  import React, { useState, useRef, useEffect, useMemo } from 'react';
2
  import ReactMarkdown from 'react-markdown';
3
  import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
4
+ import remarkMath from 'remark-math';
5
  import remarkGfm from 'remark-gfm';
6
+ import rehypeKatex from 'rehype-katex';
7
+ import 'katex/dist/katex.min.css';
8
  import Login from './Login';
9
  import './App.css';
 
 
 
 
 
10
 
11
 
12
  const LOGIC_SAYINGS = [
 
112
  "Logic enforces rationality",
113
  ];
114
 
115
+ // Preserve math blocks for KaTeX while escaping currency dollars
116
+ function preprocessMathContent(content: string): string {
117
+ // Simple approach: Just return content as-is since remarkMath handles $ delimiters
118
+ // and we want LaTeX to render. Currency escaping can be handled by the AI.
119
+ return content;
120
+ }
121
 
122
  // Eye-health optimized warm syntax highlighting theme
123
  const terminalTheme = {
 
180
  content: string;
181
  timestamp: Date;
182
  toolCalls?: ToolCall[];
183
+ thinkingContent?: string; // Intermediate working text
184
  }
185
 
186
  interface ToolCall {
 
188
  name: string;
189
  input: string;
190
  output: string;
191
+ error?: boolean; // Tool execution failed
192
+ isGenerating?: boolean; // AI is writing the code
193
+ isExecuting?: boolean; // Code is running in sandbox
194
  }
195
 
196
  interface User {
 
199
  }
200
 
201
  const GATEWAY_URL = import.meta.env.VITE_GATEWAY_URL || 'https://deepthoughtai-evo-gateway.hf.space';
202
+ console.log('App Gateway URL:', GATEWAY_URL); // Debug log
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
 
204
  function App() {
205
  const [isAuthenticated, setIsAuthenticated] = useState(false);
 
210
  const [isLoading, setIsLoading] = useState(false);
211
  const [responseComplete, setResponseComplete] = useState(false);
212
  const [statusMessage, setStatusMessage] = useState('');
 
213
  const messagesEndRef = useRef<HTMLDivElement>(null);
214
  const messagesContainerRef = useRef<HTMLDivElement>(null);
215
  const abortControllerRef = useRef<AbortController | null>(null);
216
 
217
+ // Select a random logic saying on component mount
218
  const randomSaying = useMemo(
219
  () => LOGIC_SAYINGS[Math.floor(Math.random() * LOGIC_SAYINGS.length)],
220
  []
221
  );
222
 
223
+ // Verify authentication via session on mount
224
  useEffect(() => {
225
  const verifyAuth = async () => {
226
  try {
 
234
  });
235
 
236
  if (response.ok) {
237
+ const data = await response.json();
238
+ setUser(data.user);
239
+ setIsAuthenticated(true);
 
 
 
 
 
 
 
 
240
  } else {
241
+ // Clear invalid session
242
  localStorage.removeItem('session_id');
243
  setSessionId(null);
244
  }
 
253
  }, [sessionId]);
254
 
255
  useEffect(() => {
256
+ // Only auto-scroll if user is near bottom (within 100px)
257
  const container = messagesContainerRef.current;
258
  if (container) {
259
  const isNearBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 100;
260
  if (isNearBottom) {
261
+ // Use requestAnimationFrame to avoid scroll conflicts
262
  requestAnimationFrame(() => {
263
  messagesEndRef.current?.scrollIntoView({ behavior: 'smooth', block: 'end' });
264
  });
 
283
  setResponseComplete(false);
284
  setStatusMessage('Connecting to AI model...');
285
 
286
+ // Create a temporary assistant message that will be updated
287
  const assistantId = (Date.now() + 1).toString();
288
  const assistantMessage: Message = {
289
  id: assistantId,
 
296
  setMessages((prev) => [...prev, assistantMessage]);
297
 
298
  try {
299
+ // Create new AbortController for this request
300
  abortControllerRef.current = new AbortController();
301
 
302
  const headers: HeadersInit = {
303
  'Content-Type': 'application/json'
304
  };
305
 
306
+ // Add Authorization header with session ID
307
  if (sessionId) {
308
  headers['Authorization'] = `Bearer ${sessionId}`;
309
  }
 
313
  headers,
314
  body: JSON.stringify({
315
  message: currentInput
316
+ // API key now comes from backend environment
317
  }),
318
  signal: abortControllerRef.current.signal,
319
  });
 
335
  const { done, value } = await reader.read();
336
 
337
  if (done) {
338
+ // Stream ended - immediately clear ALL loading state
339
  setIsLoading(false);
340
  setResponseComplete(true);
341
  setStatusMessage('');
 
358
  const data = JSON.parse(dataMatch[1]);
359
 
360
  if (event === 'status') {
361
+ // Update status message to show with loading indicator
362
  setStatusMessage(data.message || 'Processing...');
363
  } else if (event === 'content_chunk') {
364
+ // Stream content chunks as they arrive (like CLI)
365
+ // CRITICAL: Immediately hide spinner when content starts streaming
366
  setIsLoading(false);
367
  setResponseComplete(true);
368
  setStatusMessage('');
 
371
  prev.map((msg) => {
372
  if (msg.id !== assistantId) return msg;
373
 
374
+ // Just accumulate content directly without headers (like CLI)
375
  return {
376
  ...msg,
377
  content: (msg.content || '') + data.chunk,
 
379
  })
380
  );
381
  } else if (event === 'tool_start') {
382
+ // Add tool call placeholder with generating state
383
  setStatusMessage(`Generating ${data.name}...`);
384
  setMessages((prev) =>
385
  prev.map((msg) =>
 
402
  )
403
  );
404
  } else if (event === 'tool_executing') {
405
+ // Tool is now executing - update status
406
  setStatusMessage(`Executing ${data.name}...`);
407
  setMessages((prev) =>
408
  prev.map((msg) =>
 
419
  )
420
  );
421
  } else if (event === 'tool_complete') {
422
+ // Update tool call with result and detect errors
423
  setStatusMessage('');
424
  const output = data.output || '';
425
 
426
+ // Strategy: Check the LAST line for success/failure indicators
427
+ // This avoids false positives from status markers (❌ Not needed) in the middle
428
  const lines = output.trim().split('\n');
429
  const lastLine = lines[lines.length - 1] || '';
430
 
431
+ // Success indicators on the last line
432
  const hasFinalSuccess =
433
  lastLine.includes('✅ Classification stored') ||
434
  lastLine.includes('✅ Lean 4 code compiled successfully') ||
 
439
  /✅.*completed/i.test(lastLine) ||
440
  lastLine.includes('✅');
441
 
442
+ // Actual failure indicators (not status markers like "❌ Not needed")
443
  const hasActualFailure =
444
  output.includes('❌ BLOCKED') ||
445
  output.includes('❌ Python execution failed') ||
 
448
  output.includes('❌ Not found in Mathlib') ||
449
  output.includes('Exit code: 0') === false && /Exit code: \d+/.test(output);
450
 
451
+ // Determine error state
452
  let hasError = false;
453
  if (hasFinalSuccess) {
454
+ hasError = false; // Explicit success on last line
455
  } else if (hasActualFailure) {
456
+ hasError = true; // Explicit failure
457
  } else {
458
+ // Fallback: check for Error: prefix
459
  hasError = output.startsWith('Error:') || output.includes('\nError:');
460
  }
461
 
 
474
  )
475
  );
476
  } else if (event === 'done') {
477
+ // Stream completed - ensure all loading states are cleared
478
  setIsLoading(false);
479
  setResponseComplete(true);
480
  setStatusMessage('');
481
  } else if (event === 'error') {
482
+ // Error occurred
483
  setIsLoading(false);
484
  setResponseComplete(true);
485
  setStatusMessage('');
 
497
  }
498
  }
499
  } catch (error) {
500
+ // Don't show error message if request was aborted (user clicked New Chat)
501
  if (error instanceof Error && error.name === 'AbortError') {
502
  console.log('Request aborted by user');
503
  return;
 
518
  )
519
  );
520
  } finally {
521
+ // Final safety net - ensure ALL loading states are cleared
522
  setIsLoading(false);
523
  setResponseComplete(true);
524
  setStatusMessage('');
 
538
  const svg = btn.querySelector('svg');
539
 
540
  navigator.clipboard.writeText(content).then(() => {
541
+ // Change icon to checkmark
542
  if (svg) {
543
  const originalSVG = svg.innerHTML;
544
  svg.innerHTML = '<polyline points="20 6 9 17 4 12" stroke="currentColor" stroke-width="2.5" fill="none"></polyline>';
 
560
 
561
  let fullText = '';
562
 
563
+ // Add main message content
564
  if (message.content) {
565
  fullText += message.content + '\n\n';
566
  }
567
 
568
+ // Add all tool calls with their inputs and outputs
569
  if (message.toolCalls && message.toolCalls.length > 0) {
570
  fullText += '=== Tool Calls ===\n\n';
571
  message.toolCalls.forEach((tool, idx) => {
 
579
  }
580
 
581
  navigator.clipboard.writeText(fullText.trim()).then(() => {
582
+ // Change icon to checkmark
583
  if (svg) {
584
  const originalSVG = svg.innerHTML;
585
  svg.innerHTML = '<polyline points="20 6 9 17 4 12" stroke="currentColor" stroke-width="2.5" fill="none"></polyline>';
 
596
  };
597
 
598
  const handleLogin = (sessionId: string, userData: User) => {
599
+ // Store session ID
600
  if (sessionId) {
601
  localStorage.setItem('session_id', sessionId);
602
  setSessionId(sessionId);
 
606
  };
607
 
608
  const handleNewChat = async () => {
609
+ // Cancel any ongoing request
610
  if (abortControllerRef.current) {
611
  abortControllerRef.current.abort();
612
  abortControllerRef.current = null;
613
  }
614
 
615
+ // Clear backend conversation history
616
  try {
617
  const headers: HeadersInit = {
618
  'Content-Type': 'application/json'
 
632
  console.error('Failed to clear chat history:', error);
633
  }
634
 
635
+ // Clear frontend state
636
  setMessages([]);
637
  setInput('');
638
  setIsLoading(false);
 
655
  console.error('Logout failed:', error);
656
  }
657
 
658
+ // Clear session from localStorage
659
  localStorage.removeItem('session_id');
660
  setSessionId(null);
661
  setUser(null);
 
668
  }
669
 
670
  return (
671
+ <div className="app">
672
+ <header className="header">
673
+ <div className="header-left">
674
+ <h1 className="logo-text">evo</h1>
675
+ <span className="version">v1.0</span>
676
+ </div>
677
+ <div className="header-right">
678
+ <button
679
+ className="new-chat-btn"
680
+ onClick={handleNewChat}
681
+ style={{ marginRight: '1rem' }}
682
+ >
683
+ New Chat
684
+ </button>
685
+ <span className="user-info">👤 {user?.name}</span>
686
+ <button className="logout-btn" onClick={handleLogout}>
687
+ Logout
688
+ </button>
689
+ </div>
690
+ </header>
691
+ <div className="chat-container">
692
+ <div className="messages" ref={messagesContainerRef}>
693
+ {messages.length === 0 && (
694
+ <div className="welcome">
695
+ <div className="examples">
696
+ <h3>Try these examples:</h3>
697
+ <button onClick={() => setInput("What is the derivative of x^2 + 1?")} className="example-btn">
698
+ Calculate derivative
699
+ </button>
700
+ <button onClick={() => setInput("How many Rs in strawberry")} className="example-btn">
701
+ Count characters
702
+ </button>
703
+ <button onClick={() => setInput("Prove derivative of x^2 is 2x")} className="example-btn">
704
+ Prove a theorem
705
+ </button>
706
+ <button onClick={() => setInput("9.9 and 9.11 which is bigger?")} className="example-btn">
707
+ Compare decimals
708
+ </button>
709
+ <button onClick={() => setInput("What is a Large Language Model?")} className="example-btn">
710
+ General question
711
+ </button>
 
 
 
 
 
712
  </div>
713
+ </div>
714
+ )}
715
+ {messages.map((message) => {
716
+ // Don't render empty assistant messages while loading
717
+ if (message.role === 'assistant' && !message.content && (!message.toolCalls || message.toolCalls.length === 0)) {
718
+ return null;
719
+ }
720
+
721
+ return (
722
+ <div key={message.id} className={`message message-${message.role}`}>
723
+ <div className="message-header">
724
+ <span className="message-role">
725
+ {message.role === 'user' ? 'You' : 'Assistant'}
726
+ </span>
727
+ <div className="message-header-right">
728
+ {message.role === 'assistant' && (
 
 
 
 
 
 
 
 
 
 
 
 
 
729
  <button
730
  className="copy-markdown-btn"
731
+ onClick={(e) => copyEverything(message, e)}
732
+ title="Copy everything (including expanders)"
733
  >
734
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
735
  <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
736
  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
737
+ <circle cx="11.5" cy="11.5" r="1.5" fill="currentColor"></circle>
738
+ <circle cx="16.5" cy="11.5" r="1.5" fill="currentColor"></circle>
739
+ <circle cx="11.5" cy="16.5" r="1.5" fill="currentColor"></circle>
740
+ <circle cx="16.5" cy="16.5" r="1.5" fill="currentColor"></circle>
741
  </svg>
742
  </button>
743
+ )}
744
+ <button
745
+ className="copy-markdown-btn"
746
+ onClick={(e) => copyAsMarkdown(message.content, e)}
747
+ title="Copy as markdown"
748
+ >
749
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
750
+ <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
751
+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
752
+ </svg>
753
+ </button>
754
+ <span className="message-time">
755
+ {message.timestamp.toLocaleTimeString()}
756
+ </span>
757
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
758
  </div>
759
+ {/* Final response content */}
760
+ {message.content && (
761
+ <div className="message-content">
762
+ <ReactMarkdown
763
+ remarkPlugins={[
764
+ [remarkMath, { singleDollarTextMath: true }],
765
+ remarkGfm
766
+ ]}
767
+ rehypePlugins={[rehypeKatex]}
768
+ components={{
769
+ code({ className, children, ...props }: any) {
770
+ const match = /language-(\w+)/.exec(className || '');
771
+ return match ? (
772
+ <SyntaxHighlighter
773
+ style={terminalTheme as any}
774
+ language={match[1]}
775
+ PreTag="div"
776
+ {...props}
777
+ >
778
+ {String(children).replace(/\n$/, '')}
779
+ </SyntaxHighlighter>
780
+ ) : (
781
+ <code className={className} {...props}>
782
+ {children}
783
+ </code>
784
+ );
785
+ },
786
+ }}
787
+ >
788
+ {preprocessMathContent(message.content)}
789
+ </ReactMarkdown>
790
+ </div>
791
+ )}
792
+ {/* Tool calls - unchanged from original */}
793
+ {message.toolCalls && message.toolCalls.length > 0 && (
794
+ <div className="tool-calls">
795
+ {message.toolCalls.map((tool, idx) => (
796
+ <details key={idx} className="tool-call">
797
+ <summary className="tool-call-header">
798
+ <span className="tool-name">{tool.name}</span>
799
+ {tool.isGenerating && (
800
+ <span className="tool-status generating">
801
+ <span className="dot"></span>
802
+ <span className="dot"></span>
803
+ <span className="dot"></span>
804
+ <span className="status-text">Generating...</span>
805
+ </span>
806
+ )}
807
+ {tool.isExecuting && (
808
+ <span className="tool-status executing">
809
+ <span className="dot"></span>
810
+ <span className="dot"></span>
811
+ <span className="dot"></span>
812
+ <span className="status-text">Executing...</span>
813
+ </span>
814
+ )}
815
+ {tool.output && !tool.isGenerating && !tool.isExecuting && (
816
+ tool.error ? (
817
+ <span className="crossmark">✗</span>
818
+ ) : (
819
+ <span className="checkmark">✓</span>
820
+ )
821
+ )}
822
+ </summary>
823
+ <div className="tool-call-content">
824
+ <details className="tool-section">
825
+ <summary className="tool-section-label">Input:</summary>
826
+ <pre className="tool-code tool-input-scroll">{tool.input}</pre>
827
+ </details>
828
+ {tool.output && (
829
+ <div className="tool-section">
830
+ <div className="tool-section-label">Output:</div>
831
+ <pre className="tool-output">{tool.output}</pre>
832
+ </div>
833
+ )}
834
+ </div>
835
+ </details>
836
+ ))}
837
+ </div>
838
  )}
839
  </div>
840
+ );
841
+ })}
842
+ {/* Only show spinner if loading AND response is not complete AND no content yet in the last message */}
843
+ {isLoading && !responseComplete && (
844
+ <div className="typing-indicator">
845
+ <span></span>
846
+ <span></span>
847
+ <span></span>
848
+ <em className="status-message">{statusMessage || 'Thinking...'}</em>
849
+ </div>
850
+ )}
851
+ <div ref={messagesEndRef} />
852
+ </div>
853
+ <div className="input-container">
854
+ <textarea
855
+ value={input}
856
+ onChange={(e) => setInput(e.target.value)}
857
+ onKeyPress={handleKeyPress}
858
+ placeholder={`${randomSaying} (Shift+Enter for new line)`}
859
+ disabled={isLoading}
860
+ rows={3}
861
+ />
862
+ <button onClick={handleSendMessage} disabled={isLoading || !input.trim()} className="send-btn">
863
+ {isLoading ? 'Sending...' : 'Send'}
864
+ </button>
865
  </div>
866
  </div>
867
+ </div>
868
  );
869
  }
870
 
871
+ export default App;