fraudTech commited on
Commit
e5f49d0
·
1 Parent(s): abac006

refactor: Simplify frontend to login + streaming chat only

Browse files

- api.js: Keep only login() and streamChat()
- App.js: Remove session panel, admin register, KB upload, direct query, discover
- Keep markdown/KaTeX rendering and debug panel

Files changed (3) hide show
  1. src/App.css +9 -0
  2. src/App.js +206 -1309
  3. src/api.js +38 -487
src/App.css CHANGED
@@ -421,6 +421,15 @@ body, html, #root {
421
  color: inherit;
422
  }
423
 
 
 
 
 
 
 
 
 
 
424
  /* Blockquotes */
425
  .message .bubble blockquote {
426
  margin: 0.6rem 0;
 
421
  color: inherit;
422
  }
423
 
424
+ /* Override KaTeX red error color for dark theme */
425
+ .markdown-body .katex-error {
426
+ color: #e2e8f0 !important;
427
+ }
428
+
429
+ .markdown-body .katex .mord.text {
430
+ color: inherit;
431
+ }
432
+
433
  /* Blockquotes */
434
  .message .bubble blockquote {
435
  margin: 0.6rem 0;
src/App.js CHANGED
@@ -1,39 +1,21 @@
1
  // src/App.js
2
 
3
- import React, { useState } from "react";
4
- import { useMemo } from "react";
5
- import {
6
- sendChat,
7
- login,
8
- streamChat,
9
- uploadPrologFile,
10
- getKBMetadata,
11
- queryProlog,
12
- getMe,
13
- registerUser,
14
- listSessionLemmas,
15
- listSessionDocs,
16
- clearSession,
17
- exportSessionLemmas,
18
- rollbackSessionPromotion,
19
- promoteSessionLemmas,
20
- discoverMath,
21
- proveGoal,
22
- ingestArxivToSession,
23
- ingestStoryToSession,
24
- } from "./api";
25
  import "./App.css";
26
 
27
  import ReactMarkdown from "react-markdown";
28
  import remarkMath from "remark-math";
29
  import rehypeKatex from "rehype-katex";
30
  import "katex/dist/katex.min.css";
31
-
32
  import remarkGfm from "remark-gfm";
33
 
 
 
 
34
  const LOGIC_SAYINGS = [
35
  "Logic is the compass; reason is the journey.",
36
- "Logic doesn't tell you where to go—only how not to get lost.",
37
  "Emotion starts the fire; logic builds the fireplace.",
38
  "Logic is truth with the noise removed.",
39
  "Where logic ends, belief begins.",
@@ -45,173 +27,96 @@ const LOGIC_SAYINGS = [
45
  "Logic is thinking that survives inspection.",
46
  "Feelings persuade; logic convinces.",
47
  "Logic is the skeleton beneath every solid idea.",
48
- "Logic doesn't shout—it explains.",
49
  "Logic is humility formalized.",
50
- "Logic is the courage to follow conclusions you don't like.",
51
  "Logic is what remains when excuses are removed.",
52
- "Logic sharpens truth; rhetoric polishes it.",
53
  "Logic is slow thinking that wins.",
54
  "Logic is the art of necessary consequences.",
55
- "Logic is not cold—it's honest.",
56
- "Logic is curiosity wearing rules.",
57
- "Logic asks 'must it be so?'",
58
  "Logic is the bridge between assumptions and reality.",
59
  "Logic is doubt with a method.",
60
  "Logic is reason refusing shortcuts.",
61
- "Logic is the map; wisdom chooses the destination.",
62
- "Logic doesn't prevent mistakes—it exposes them early.",
63
  "Logic is clarity earned, not assumed.",
64
- "Logic is discipline against wishful thinking.",
65
- "Logic is what makes disagreement productive.",
66
- "Logic is thinking that scales beyond yourself.",
67
- "Logic is the grammar of truth.",
68
- "Logic is consistency under pressure.",
69
  "Logic is the enemy of convenient nonsense.",
70
- "Logic doesn't care who you are—only what follows.",
71
  "Logic is freedom from contradiction.",
72
- "Logic is order negotiated with reality.",
73
- "Logic is the courage to say 'I was wrong.'",
74
- "Logic is thinking that respects consequences.",
75
  "Logic is precision applied to belief.",
76
- "Logic is restraint in an impatient world.",
77
  "Logic is the difference between opinion and argument.",
78
- "Logic is clarity without charisma.",
79
  "Logic is trust in structure over impulse.",
80
- "Logic is reasoning with receipts.",
81
  "Logic is thought that can be audited.",
82
  "Logic is the firewall against self-deception.",
83
- "Logic is patience encoded.",
84
- "Logic is a promise to be consistent tomorrow.",
85
- "Logic is the refusal to confuse desire with evidence.",
86
- "Logic is the backbone of fairness.",
87
- "Logic is what makes intelligence reliable.",
88
- "Logic is the art of not contradicting yourself later.",
89
- "Logic is explanation that survives time.",
90
  "Logic is truth, step by step.",
91
- "Logic is the science of 'therefore.'",
92
- "Logic is clarity that doesn't depend on mood.",
93
  "Logic is thinking that welcomes scrutiny.",
94
- "Logic is humility with equations.",
95
  "Logic is the difference between sounding right and being right.",
96
- "Logic is reason trained to behave.",
97
- "Logic is structure applied to curiosity.",
98
  "Logic is belief with a warranty.",
99
- "Logic is the discipline of necessary steps.",
100
  "Logic is calm thinking in loud situations.",
101
- "Logic is the art of implication.",
102
- "Logic is skepticism with standards.",
103
- "Logic is thinking that keeps promises.",
104
  "Logic is the architecture of understanding.",
105
- "Logic is what lets truth travel intact.",
106
- "Logic is order discovered, not imposed.",
107
- "Logic is reasoning that scales beyond intuition.",
108
  "Logic is the slow weapon against fast lies.",
109
  "Logic is consistency made explicit.",
110
- "Logic is thinking that earns trust.",
111
- "Logic is precision without arrogance.",
112
- "Logic is explanation that doesn't flinch.",
113
- "Logic is thought that survives opposition.",
114
  "Logic is truth under constraints.",
115
- "Logic is discipline for the curious.",
116
  "Logic is evidence wearing syntax.",
117
  "Logic is the guardrail of intelligence.",
118
- "Logic is belief forced to grow up.",
119
  "Logic is the art of unavoidable conclusions.",
120
- "Logic is patience that pays interest.",
121
  "Logic is reasoning that respects reality.",
122
- "Logic is clarity that doesn't need applause.",
123
  "Logic is the structure beneath insight.",
124
- "Logic is the courage to follow 'if–then.'",
125
- "Logic is thinking that refuses special treatment.",
126
- "Logic is what makes truth transferable.",
127
- "Logic is the economy of thought.",
128
  "Logic is understanding without shortcuts.",
129
- "Logic is precision in motion.",
130
  "Logic is thought with integrity.",
131
- "Logic is explanation that doesn't leak.",
132
  "Logic is the science of consistency.",
133
- "Logic is freedom from internal contradiction.",
134
- "Logic is respect—for truth, for thought, and for consequence.",
135
  ];
136
 
 
 
 
137
  function normalizeLatex(text) {
138
  if (!text) return "";
139
-
140
- let normalized = text;
141
-
142
- // Replace \[...\] with $$...$$
143
- normalized = normalized.replace(/\\\[(.+?)\\\]/gs, (_, inner) => `$$${inner}$$`);
144
-
145
- // Replace \(...\) with $...$
146
- normalized = normalized.replace(/\\\((.+?)\\\)/gs, (_, inner) => `$${inner}$`);
147
-
148
- // Fix multiple dollar signs issues
149
- // Fix quadruple dollar signs $$$$ back to $$
150
- normalized = normalized.replace(/\$\$\$\$/g, '$$');
151
-
152
- // Fix triple dollar signs $$$ back to $$
153
- normalized = normalized.replace(/\$\$\$/g, '$$');
154
-
155
- // Fix standalone $ with $x$ patterns that might be broken
156
- // Ensure proper spacing around inline math
157
- normalized = normalized.replace(/\$([^\$\n]+?)\$/g, (match, inner) => {
158
- // Trim whitespace from the math expression
159
- const trimmed = inner.trim();
160
- return `$${trimmed}$`;
161
- });
162
-
163
- // Fix display math with extra whitespace
164
- normalized = normalized.replace(/\$\$([^\$]+?)\$\$/gs, (match, inner) => {
165
- // Preserve internal structure but trim outer whitespace
166
- const trimmed = inner.trim();
167
- return `$$${trimmed}$$`;
168
  });
169
-
170
- return normalized;
171
  }
172
 
173
- // DebugExpander component for collapsible debug sections
 
 
174
  function DebugExpander({ title, defaultOpen = false, children }) {
175
- const [isOpen, setIsOpen] = useState(defaultOpen);
176
-
177
  return (
178
- <div style={{ marginBottom: "12px" }}>
179
  <button
180
- onClick={() => setIsOpen(!isOpen)}
181
  style={{
182
- width: "100%",
183
- textAlign: "left",
184
- padding: "8px 12px",
185
- background: isOpen ? "#e8f4f8" : "#fff",
186
- border: "1px solid #ccc",
187
- borderRadius: "4px",
188
- cursor: "pointer",
189
- display: "flex",
190
- alignItems: "center",
191
- justifyContent: "space-between",
192
- fontWeight: "600",
193
- color: "#1a1a1a",
194
- fontSize: "0.9em"
195
  }}
196
  >
197
  <span>{title}</span>
198
- <span style={{
199
- fontSize: "1.2em",
200
- transform: isOpen ? "rotate(90deg)" : "rotate(0deg)",
201
- transition: "transform 0.2s",
202
- display: "inline-block"
203
- }}>
204
- ▶
205
- </span>
206
  </button>
207
- {isOpen && (
208
- <div style={{
209
- marginTop: "8px",
210
- padding: "10px",
211
- background: "#fff",
212
- border: "1px solid #e2e2e2",
213
- borderRadius: "4px"
214
- }}>
215
  {children}
216
  </div>
217
  )}
@@ -219,532 +124,225 @@ function DebugExpander({ title, defaultOpen = false, children }) {
219
  );
220
  }
221
 
222
- function App() {
223
- // ---------------------------
224
- // Random Logic Saying
225
- // ---------------------------
226
- const randomSaying = useMemo(() => {
227
- return LOGIC_SAYINGS[Math.floor(Math.random() * LOGIC_SAYINGS.length)];
228
- }, []);
229
 
230
- // ---------------------------
231
- // Authentication State
232
- // ---------------------------
233
- const [token, setToken] = useState(null);
234
- const [authError, setAuthError] = useState(null);
235
- const [me, setMe] = useState(null);
236
- const [loginForm, setLoginForm] = useState({
237
- username: "",
238
- password: "",
239
- });
240
 
241
- // ---------------------------
242
- // Chat State
243
- // ---------------------------
244
 
245
- const [messages, setMessages] = useState([]);
 
 
 
246
 
247
- const [input, setInput] = useState("");
248
- const [strictMode, setStrictMode] = useState(true);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
 
250
- // Session trigger - increment to force new sessionId generation
251
- const [sessionTrigger, setSessionTrigger] = useState(0);
 
 
 
 
 
 
 
 
 
 
 
252
 
253
- // Session-scoped KB staging uses this stable id.
254
- const sessionId = useMemo(() => {
255
- try {
256
- if (typeof crypto !== "undefined" && crypto.randomUUID) {
257
- return crypto.randomUUID();
258
- }
259
- } catch {
260
- // ignore
261
- }
262
- return `sid-${Date.now()}-${Math.random().toString(16).slice(2)}`;
263
- }, [sessionTrigger]);
264
- const [loading, setLoading] = useState(false);
265
- const [isValidating, setIsValidating] = useState(false);
266
- const [loadingStatus, setLoadingStatus] = useState("");
267
- const [error, setError] = useState(null);
268
-
269
- // Streaming preview (first response)
270
- const [streamingPreview, setStreamingPreview] = useState(null);
271
 
272
- // ---------------------------
273
- // KB Upload State
274
- // ---------------------------
275
- const [uploadStatus, setUploadStatus] = useState(null);
276
- const [kbMetadata, setKbMetadata] = useState(null);
277
- const [showUpload, setShowUpload] = useState(false);
278
- const [showQueryPanel, setShowQueryPanel] = useState(false);
279
- const [showRegisterPanel, setShowRegisterPanel] = useState(false);
280
- const [showSessionPanel, setShowSessionPanel] = useState(false);
281
 
282
- // Session Memory UI state
283
- const [sessionLemmas, setSessionLemmas] = useState([]);
284
- const [sessionDocs, setSessionDocs] = useState({ papers: [], stories: [] });
285
- const [sessionPanelStatus, setSessionPanelStatus] = useState(null);
286
- const [sessionPanelLoading, setSessionPanelLoading] = useState(false);
 
 
 
 
 
 
 
287
 
288
- // Ingestion UI state
289
- const [arxivIdInput, setArxivIdInput] = useState("");
290
- const [storyUrlInput, setStoryUrlInput] = useState("");
 
 
 
 
 
 
 
 
 
 
 
291
 
292
- // ---------------------------
293
- // Admin Register State
294
- // ---------------------------
295
- const [registerForm, setRegisterForm] = useState({
296
- username: "",
297
- password: "",
298
- overwrite: false,
299
- });
300
- const [registerStatus, setRegisterStatus] = useState(null);
 
 
301
 
302
- // ---------------------------
303
- // Direct Query State
304
- // ---------------------------
305
- const [directQuery, setDirectQuery] = useState("");
306
- const [queryResults, setQueryResults] = useState(null);
 
 
 
307
 
308
- // Proof Trace State
309
- const [proofResult, setProofResult] = useState(null);
310
- const [proofLoading, setProofLoading] = useState(false);
311
- const [proofStatus, setProofStatus] = useState(null);
312
 
313
- // ⭐ AUTO-SCROLL WHENEVER MESSAGES CHANGE ⭐
314
- React.useEffect(() => {
315
- const container = document.querySelector(".messages");
316
- if (container) {
317
- container.scrollTop = container.scrollHeight;
318
- }
319
- }, [messages]);
320
 
 
 
 
 
 
 
321
 
322
- // ============================================================
323
- // LOAD CURRENT USER INFO (after login / token change)
324
- // ============================================================
325
  React.useEffect(() => {
326
- let cancelled = false;
327
-
328
- async function loadMe() {
329
- if (!token) {
330
- setMe(null);
331
- return;
332
- }
333
-
334
- try {
335
- const res = await getMe(token);
336
- if (!cancelled) setMe(res);
337
- } catch {
338
- // If token becomes invalid, leave UI working; API calls will fail.
339
- if (!cancelled) setMe(null);
340
- }
341
- }
342
-
343
- loadMe();
344
- return () => {
345
- cancelled = true;
346
- };
347
- }, [token]);
348
-
349
 
350
- // ============================================================
351
- // LOGIN HANDLER
352
- // ============================================================
353
  async function handleLogin(e) {
354
  e.preventDefault();
355
  setAuthError(null);
356
-
357
  try {
358
  const res = await login(loginForm.username, loginForm.password);
359
- setToken(res.token); // Save JWT
360
- setAuthError(null);
361
  } catch (err) {
362
  setAuthError(err.message || "Login failed");
363
  }
364
  }
365
 
366
- // ============================================================
367
- // REGISTER USER HANDLER (ADMIN)
368
- // ============================================================
369
- async function handleRegisterUser(e) {
370
- e.preventDefault();
371
- setRegisterStatus(null);
372
-
373
- const username = (registerForm.username || "").trim();
374
- const password = (registerForm.password || "").trim();
375
- if (!username || !password) {
376
- setRegisterStatus("Error: Missing username or password");
377
- return;
378
- }
379
-
380
- try {
381
- const result = await registerUser(username, password, token, registerForm.overwrite);
382
- setRegisterStatus(`Created user: ${result.username}`);
383
- setRegisterForm({ username: "", password: "", overwrite: false });
384
- } catch (err) {
385
- setRegisterStatus(`Error: ${err.message}`);
386
- }
387
- }
388
-
389
- // ============================================================
390
- // FILE UPLOAD HANDLER
391
- // ============================================================
392
- async function handleFileUpload(e) {
393
- const file = e.target.files[0];
394
- if (!file) return;
395
-
396
- setUploadStatus("Uploading...");
397
- try {
398
- const text = await file.text();
399
- const result = await uploadPrologFile(text, token);
400
- setUploadStatus(result.message || "Upload successful!");
401
-
402
- // Refresh metadata
403
- const metadata = await getKBMetadata(token);
404
- setKbMetadata(metadata.metadata);
405
- } catch (err) {
406
- setUploadStatus(`Error: ${err.message}`);
407
- }
408
- }
409
-
410
- // ============================================================
411
- // LOAD KB METADATA
412
- // ============================================================
413
- async function handleLoadMetadata() {
414
- try {
415
- const result = await getKBMetadata(token);
416
- setKbMetadata(result.metadata);
417
- } catch (err) {
418
- setKbMetadata(`Error: ${err.message}`);
419
- }
420
- }
421
-
422
- // ============================================================
423
- // DIRECT PROLOG QUERY
424
- // ============================================================
425
- async function handleDirectQuery(e) {
426
- e.preventDefault();
427
- if (!directQuery.trim()) return;
428
-
429
- try {
430
- const result = await queryProlog(directQuery, token);
431
- setQueryResults(result.solutions);
432
- } catch (err) {
433
- setQueryResults([{ error: err.message }]);
434
- }
435
- }
436
-
437
-
438
- async function handleProveGoal(e) {
439
- e.preventDefault();
440
- if (!directQuery.trim()) return;
441
- if (!token) return;
442
-
443
- const goal = (directQuery || "").trim().replace(/\.\s*$/, "");
444
- setProofStatus(null);
445
- setProofLoading(true);
446
- try {
447
- const res = await proveGoal(goal, token);
448
- setProofResult(res);
449
- setProofStatus("Proof trace generated.");
450
- } catch (err) {
451
- setProofResult({ error: err.message });
452
- setProofStatus(`Error: ${err.message}`);
453
- } finally {
454
- setProofLoading(false);
455
- }
456
- }
457
-
458
-
459
- // ============================================================
460
- // SESSION MEMORY (list / clear / discover&stage)
461
- // ============================================================
462
- async function refreshSessionMemory({ clearStatus = true } = {}) {
463
- if (!token) return;
464
- if (clearStatus) setSessionPanelStatus(null);
465
- setSessionPanelLoading(true);
466
- try {
467
- const res = await listSessionLemmas(sessionId, token);
468
- setSessionLemmas(res.lemmas || []);
469
- try {
470
- const docs = await listSessionDocs(sessionId, token);
471
- setSessionDocs({ papers: docs.papers || [], stories: docs.stories || [] });
472
- } catch {
473
- // ignore
474
- }
475
- } catch (err) {
476
- setSessionPanelStatus(`Error: ${err.message}`);
477
- } finally {
478
- setSessionPanelLoading(false);
479
- }
480
- }
481
-
482
- async function handleIngestArxiv() {
483
- if (!token) return;
484
- setSessionPanelStatus(null);
485
- setSessionPanelLoading(true);
486
- try {
487
- const id = (arxivIdInput || "").trim();
488
- if (!id) {
489
- setSessionPanelStatus("Error: Missing arXiv id (or URL). ");
490
- return;
491
- }
492
- const res = await ingestArxivToSession(sessionId, token, id, 200, false);
493
- const stagedParas = res.staged && typeof res.staged.paragraphs === "number" ? res.staged.paragraphs : null;
494
- setSessionPanelStatus(
495
- stagedParas !== null
496
- ? `Ingested ${res.arxiv_id || id} and staged ${stagedParas} paragraphs into this session.`
497
- : `Ingested ${res.arxiv_id || id} into this session.`
498
- );
499
- await refreshSessionMemory({ clearStatus: false });
500
- } catch (err) {
501
- setSessionPanelStatus(`Error: ${err.message}`);
502
- } finally {
503
- setSessionPanelLoading(false);
504
- }
505
- }
506
-
507
- async function handleIngestStory() {
508
- if (!token) return;
509
- setSessionPanelStatus(null);
510
- setSessionPanelLoading(true);
511
- try {
512
- const url = (storyUrlInput || "").trim();
513
- if (!url) {
514
- setSessionPanelStatus("Error: Missing story URL.");
515
- return;
516
- }
517
- const res = await ingestStoryToSession(sessionId, token, url, "story", "", 200);
518
- const stagedParas = res.staged && typeof res.staged.paragraphs === "number" ? res.staged.paragraphs : null;
519
- setSessionPanelStatus(
520
- stagedParas !== null
521
- ? `Ingested story and staged ${stagedParas} paragraphs into this session.`
522
- : "Ingested story into this session."
523
- );
524
- await refreshSessionMemory({ clearStatus: false });
525
- } catch (err) {
526
- setSessionPanelStatus(`Error: ${err.message}`);
527
- } finally {
528
- setSessionPanelLoading(false);
529
- }
530
- }
531
-
532
- async function handleClearSessionMemory() {
533
- if (!token) return;
534
- setSessionPanelStatus(null);
535
- setSessionPanelLoading(true);
536
- try {
537
- await clearSession(sessionId, token);
538
- setSessionLemmas([]);
539
- setSessionPanelStatus("Cleared session memory.");
540
- } catch (err) {
541
- setSessionPanelStatus(`Error: ${err.message}`);
542
- } finally {
543
- setSessionPanelLoading(false);
544
- }
545
- }
546
-
547
- async function handleDiscoverAndStage() {
548
- if (!token) return;
549
- setSessionPanelStatus(null);
550
- setSessionPanelLoading(true);
551
-
552
- const currentInput = (input || "").trim();
553
- let question = currentInput;
554
- if (!question) {
555
- const lastUser = [...messages].reverse().find((m) => m && m.role === "user" && (m.text || "").trim());
556
- question = lastUser ? (lastUser.text || "").trim() : "";
557
- }
558
-
559
- if (!question) {
560
- setSessionPanelStatus("Error: No question available to discover from. Type a question first.");
561
- setSessionPanelLoading(false);
562
- return;
563
- }
564
-
565
- try {
566
- setSessionPanelStatus("Running math discovery (hybrid validation)…");
567
- const res = await discoverMath(question, token, sessionId, 12, 250, true);
568
- const staged = res.staged;
569
- if (staged && staged.ok) {
570
- const stagedCount = typeof staged.staged === "number" ? staged.staged : null;
571
- setSessionPanelStatus(
572
- stagedCount !== null
573
- ? `Discovery staged ${stagedCount} validated lemma(s) into this session.`
574
- : "Discovery staged validated lemmas into this session."
575
- );
576
- } else if (staged && staged.error) {
577
- setSessionPanelStatus(`Discovery ran, but staging failed: ${staged.error}`);
578
- } else {
579
- setSessionPanelStatus("Discovery completed.");
580
- }
581
- await refreshSessionMemory({ clearStatus: false });
582
- } catch (err) {
583
- setSessionPanelStatus(`Error: ${err.message}`);
584
- } finally {
585
- setSessionPanelLoading(false);
586
- }
587
- }
588
-
589
- async function handleExportSessionMemory() {
590
- if (!token) return;
591
- setSessionPanelStatus(null);
592
- setSessionPanelLoading(true);
593
- try {
594
- const res = await exportSessionLemmas(sessionId, token, "exported_from_ui");
595
- const file = res.file || "(unknown file)";
596
- const exported = typeof res.exported === "number" ? res.exported : null;
597
- setSessionPanelStatus(
598
- exported !== null
599
- ? `Exported ${exported} validated lemma(s) to: ${file}`
600
- : `Exported learned lemmas to: ${file}`
601
- );
602
- } catch (err) {
603
- setSessionPanelStatus(`Error: ${err.message}`);
604
- } finally {
605
- setSessionPanelLoading(false);
606
- }
607
- }
608
-
609
- async function handlePromoteSessionMemory() {
610
- if (!token) return;
611
- setSessionPanelStatus(null);
612
- setSessionPanelLoading(true);
613
- try {
614
- const res = await promoteSessionLemmas(sessionId, token, "promoted_from_ui", true);
615
- const file = res.file || "(unknown file)";
616
- const promoted = typeof res.promoted === "number" ? res.promoted : null;
617
- setSessionPanelStatus(
618
- promoted !== null
619
- ? `Promoted ${promoted} lemma(s) (bench-gated) to: ${file}`
620
- : `Promotion completed (bench-gated). File: ${file}`
621
- );
622
- } catch (err) {
623
- setSessionPanelStatus(`Error: ${err.message}`);
624
- } finally {
625
- setSessionPanelLoading(false);
626
- }
627
- }
628
-
629
- async function handleRollbackPromotion() {
630
- if (!token) return;
631
- setSessionPanelStatus(null);
632
- setSessionPanelLoading(true);
633
- try {
634
- const res = await rollbackSessionPromotion(sessionId, token, false);
635
- setSessionPanelStatus(`Rolled back promotion: ${res.file || "(unknown file)"}`);
636
- } catch (err) {
637
- setSessionPanelStatus(`Error: ${err.message}`);
638
- } finally {
639
- setSessionPanelLoading(false);
640
- }
641
- }
642
-
643
- React.useEffect(() => {
644
- if (showSessionPanel && token) {
645
- refreshSessionMemory();
646
- }
647
- // eslint-disable-next-line react-hooks/exhaustive-deps
648
- }, [showSessionPanel, token]);
649
-
650
- // ============================================================
651
- // NEW CHAT SESSION
652
- // ============================================================
653
  function handleNewChat() {
654
  setMessages([]);
655
  setInput("");
656
  setError(null);
657
- setSessionTrigger(prev => prev + 1);
658
- // Optionally clear session panels
659
- setSessionLemmas([]);
660
- setSessionDocs({ papers: [], stories: [] });
661
- setSessionPanelStatus(null);
662
  }
663
 
664
- // ============================================================
665
- // SEND CHAT MESSAGE
666
- // ============================================================
667
  async function handleSend(e) {
668
  if (e) e.preventDefault();
669
  if (!input.trim() || loading || !token) return;
670
 
671
  const userMsg = { role: "user", text: input.trim() };
672
- const newMessages = [...messages, userMsg];
673
-
674
- // Create empty assistant bubble for streaming.
675
- // We render a "Thinking..." placeholder while text is still empty.
676
- const assistantMsg = { role: "assistant", text: "", debug: null, thinking: true, statusText: "", loadingDebug: false };
677
- newMessages.push(assistantMsg);
678
-
679
  setMessages(newMessages);
680
  setInput("");
681
  setError(null);
682
  setLoading(true);
683
- setLoadingStatus("Processing your query...");
684
 
685
  try {
686
- const historyForBackend = newMessages.map((m) => ({
687
- role: m.role,
688
- content: m.text,
689
- }));
690
-
691
- // STREAM HERE ⬇⬇⬇
692
- setLoadingStatus("Streaming response...");
693
- assistantMsg.statusText = "Processing query...";
694
- setMessages([...newMessages]);
695
  await streamChat(
696
  userMsg.text,
697
- strictMode,
698
- historyForBackend,
699
  token,
700
  (chunk) => {
701
- if (assistantMsg.thinking && !(assistantMsg.text || "").trim()) {
702
  assistantMsg.text = chunk;
703
  assistantMsg.thinking = false;
704
- assistantMsg.statusText = ""; // Clear status when content arrives
705
  } else {
706
- assistantMsg.text += chunk; // append chunk
707
  }
708
- setMessages([...newMessages]); // re-render UI
709
  },
710
  sessionId,
711
  (statusMsg) => {
712
- // Handle status updates from backend - only show if not streaming content yet
713
- if (!assistantMsg.text || assistantMsg.text.trim() === "") {
714
  assistantMsg.statusText = statusMsg;
715
- assistantMsg.thinking = true; // Keep showing thinking animation while processing
716
  setMessages([...newMessages]);
717
  }
718
  },
719
  (debugData) => {
720
- // Debug info received at end of stream - instant!
721
- console.log("Debug callback triggered with:", debugData);
722
  assistantMsg.debug = debugData;
723
- assistantMsg.loadingDebug = false;
724
  setMessages([...newMessages]);
725
  }
726
  );
727
-
728
- // Finalize the streaming response
729
  assistantMsg.thinking = false;
730
  assistantMsg.statusText = "";
731
- assistantMsg.loadingDebug = false;
732
  setMessages([...newMessages]);
733
-
734
  } catch (err) {
735
  assistantMsg.thinking = false;
736
  assistantMsg.text += `\n[Error: ${err.message}]`;
737
  setMessages([...newMessages]);
738
  } finally {
739
  setLoading(false);
740
- setLoadingStatus("");
741
  }
742
  }
743
 
744
-
745
- // ============================================================
746
- // LOGIN SCREEN (shown if no token)
747
- // ============================================================
748
  if (!token) {
749
  return (
750
  <div className="app-root">
@@ -754,22 +352,10 @@ function App() {
754
  <main className="main login">
755
  <form className="login-form" onSubmit={handleLogin}>
756
  <h2>Sign In</h2>
757
- <input
758
- type="text"
759
- placeholder="Username"
760
- value={loginForm.username}
761
- onChange={(e) =>
762
- setLoginForm({ ...loginForm, username: e.target.value })
763
- }
764
- />
765
- <input
766
- type="password"
767
- placeholder="Password"
768
- value={loginForm.password}
769
- onChange={(e) =>
770
- setLoginForm({ ...loginForm, password: e.target.value })
771
- }
772
- />
773
  <button type="submit">Log In</button>
774
  {authError && <div className="error">{authError}</div>}
775
  </form>
@@ -778,133 +364,28 @@ function App() {
778
  );
779
  }
780
 
781
- // ============================================================
782
- // CHAT UI (visible only when logged in)
783
- // ============================================================
784
  return (
785
  <div className="app-root">
786
  <header className="header">
787
  <h1 className="header-title">Prolog AI</h1>
788
  <div className="header-actions">
789
- <button
790
- className="btn-secondary"
791
- onClick={handleNewChat}
792
- title="New Chat Session"
793
- >
794
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
795
- <path d="M12 5v14M5 12h14"/>
796
- </svg>
797
- </button>
798
- <button
799
- className="strict-toggle-btn"
800
- onClick={() => {
801
- setStrictMode(!strictMode);
802
- setMessages([]);
803
- }}
804
- title={strictMode ? "Strict KB Mode (click to disable)" : "Flexible Mode (click to enable strict mode)"}
805
- >
806
- {strictMode ? (
807
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
808
- <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
809
- <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
810
- </svg>
811
- ) : (
812
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
813
- <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
814
- <path d="M7 11V7a5 5 0 0 1 9.9-1"/>
815
- </svg>
816
- )}
817
- </button>
818
- <button
819
- className="btn-secondary"
820
- onClick={() => setShowQueryPanel(!showQueryPanel)}
821
- title="Query KB"
822
- >
823
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
824
- <circle cx="11" cy="11" r="8"/>
825
- <path d="m21 21-4.35-4.35"/>
826
  </svg>
827
  </button>
828
- <button
829
- className="btn-secondary"
830
- onClick={() => {
831
- setShowSessionPanel((v) => !v);
832
- setShowQueryPanel(false);
833
- setShowRegisterPanel(false);
834
- }}
835
- title="Session Memory"
836
- >
837
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
838
- <ellipse cx="12" cy="5" rx="9" ry="3"/>
839
- <path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/>
840
- <path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/>
841
- </svg>
842
- </button>
843
- {me && me.is_admin && (
844
- <button
845
- className="btn-secondary"
846
- onClick={() => {
847
- setShowRegisterPanel((v) => !v);
848
- setShowQueryPanel(false);
849
- }}
850
- title="Register User"
851
- >
852
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
853
- <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
854
- <circle cx="12" cy="7" r="4"/>
855
- </svg>
856
- </button>
857
- )}
858
- <button
859
- className="logout-btn"
860
- onClick={() => {
861
- setToken(null);
862
- setMe(null);
863
- setShowUpload(false);
864
- setShowQueryPanel(false);
865
- setShowRegisterPanel(false);
866
- setShowSessionPanel(false);
867
- setRegisterStatus(null);
868
- }}
869
- title="Logout"
870
- >
871
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
872
- <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
873
- <polyline points="16 17 21 12 16 7"/>
874
- <line x1="21" y1="12" x2="9" y2="12"/>
875
  </svg>
876
  </button>
877
  </div>
878
  </header>
 
879
  <div className="app-container">
880
- {/* Streaming Preview Panel - Left */}
881
- {streamingPreview && (
882
- <aside className="sidebar streaming-preview-sidebar">
883
- <h3>Streaming Preview</h3>
884
- <p style={{ fontSize: "0.85em", color: "#888", marginBottom: "10px" }}>
885
- First response (before validation)
886
- </p>
887
- <div className="preview-content">
888
- <ReactMarkdown
889
- className="markdown-body"
890
- remarkPlugins={[remarkMath, remarkGfm]}
891
- rehypePlugins={[[rehypeKatex, { strict: "ignore", throwOnError: false, trust: true }]]}
892
- skipHtml={false}
893
- breaks={true}
894
- >
895
- {normalizeLatex(streamingPreview)}
896
- </ReactMarkdown>
897
- </div>
898
- <button
899
- onClick={() => setStreamingPreview(null)}
900
- style={{ marginTop: "10px", width: "100%" }}
901
- >
902
- Close Preview
903
- </button>
904
- </aside>
905
- )}
906
-
907
- {/* Main Chat Area */}
908
  <main className="main">
909
  <div className="messages">
910
  {messages.map((msg, idx) => (
@@ -918,600 +399,16 @@ function App() {
918
  value={input}
919
  onChange={(e) => setInput(e.target.value)}
920
  onKeyDown={(e) => {
921
- if (e.key === "Enter" && !e.shiftKey) {
922
- e.preventDefault();
923
- handleSend();
924
- }
925
  }}
926
  disabled={loading}
927
  rows="2"
928
  />
929
- {loading && isValidating && (
930
- <div style={{
931
- display: 'flex',
932
- alignItems: 'center',
933
- gap: '8px',
934
- marginLeft: '12px',
935
- color: '#a0a0a0',
936
- fontSize: '0.9em'
937
- }}>
938
- <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ animation: "spin 1s linear infinite" }}>
939
- <path d="M21 12a9 9 0 1 1-6.219-8.56"/>
940
- </svg>
941
- <span>{loadingStatus || "Validating..."}</span>
942
- </div>
943
- )}
944
  </form>
945
  </main>
946
- {/* Right Sidebar - Direct Query Panel */}
947
- {showQueryPanel && (
948
- <aside className="sidebar right-sidebar">
949
- <h3>Direct Prolog Query</h3>
950
- <p style={{ fontSize: "0.9em", color: "#666" }}>
951
- Execute raw Prolog queries directly
952
- </p>
953
- <form onSubmit={handleDirectQuery}>
954
- <textarea
955
- placeholder="Enter Prolog query (e.g., capability(X))"
956
- value={directQuery}
957
- onChange={(e) => setDirectQuery(e.target.value)}
958
- rows="3"
959
- style={{ width: "100%", marginTop: "10px" }}
960
- />
961
- <button type="submit" style={{ marginTop: "10px", width: "100%" }}>
962
- Execute Query
963
- </button>
964
- <button
965
- type="button"
966
- onClick={handleProveGoal}
967
- style={{ marginTop: "10px", width: "100%" }}
968
- disabled={proofLoading}
969
- >
970
- {proofLoading ? "Proving..." : "Prove Goal (Trace)"}
971
- </button>
972
- </form>
973
- {queryResults && (
974
- <div className="query-results" style={{ marginTop: "15px" }}>
975
- <h4>Results</h4>
976
- <pre style={{ fontSize: "0.85em", overflowX: "auto" }}>
977
- {JSON.stringify(queryResults, null, 2)}
978
- </pre>
979
- </div>
980
- )}
981
- {proofStatus && (
982
- <div className="status-message" style={{ marginTop: "10px" }}>
983
- {proofStatus}
984
- </div>
985
- )}
986
- {proofResult && (
987
- <div className="query-results" style={{ marginTop: "15px" }}>
988
- <h4>Proof Trace</h4>
989
- <pre style={{ fontSize: "0.85em", overflowX: "auto" }}>
990
- {JSON.stringify(proofResult, null, 2)}
991
- </pre>
992
- </div>
993
- )}
994
- </aside>
995
- )}
996
- {/* Right Sidebar - Admin Register Panel */}
997
- {showRegisterPanel && me && me.is_admin && (
998
- <aside className="sidebar right-sidebar">
999
- <h3>Register User</h3>
1000
- <p style={{ fontSize: "0.9em", color: "#666" }}>
1001
- Create a new user account (admin only)
1002
- </p>
1003
- <form onSubmit={handleRegisterUser}>
1004
- <input
1005
- type="text"
1006
- placeholder="Username"
1007
- value={registerForm.username}
1008
- onChange={(e) => setRegisterForm({ ...registerForm, username: e.target.value })}
1009
- style={{ width: "100%", marginTop: "10px" }}
1010
- />
1011
- <input
1012
- type="password"
1013
- placeholder="Password"
1014
- value={registerForm.password}
1015
- onChange={(e) => setRegisterForm({ ...registerForm, password: e.target.value })}
1016
- style={{ width: "100%", marginTop: "10px" }}
1017
- />
1018
- <label style={{ display: "flex", alignItems: "center", gap: "8px", marginTop: "10px" }}>
1019
- <input
1020
- type="checkbox"
1021
- checked={registerForm.overwrite}
1022
- onChange={(e) => setRegisterForm({ ...registerForm, overwrite: e.target.checked })}
1023
- />
1024
- Overwrite if user exists
1025
- </label>
1026
- <button type="submit" style={{ marginTop: "10px", width: "100%" }}>
1027
- Create User
1028
- </button>
1029
- </form>
1030
- {registerStatus && (
1031
- <div className="status-message" style={{ marginTop: "10px" }}>
1032
- {registerStatus}
1033
- </div>
1034
- )}
1035
- </aside>
1036
- )}
1037
- {/* Right Sidebar - Session Data Panel */}
1038
- {showSessionPanel && (
1039
- <aside className="sidebar right-sidebar">
1040
- <h3>Session Data</h3>
1041
- <p style={{ fontSize: "0.9em", color: "#666" }}>
1042
- Import data sources for this session (cleared when session ends).
1043
- </p>
1044
- <div style={{ fontSize: "0.85em", color: "#666", wordBreak: "break-all" }}>
1045
- Session ID: {sessionId}
1046
- </div>
1047
- {/* Upload Knowledge Base Section */}
1048
- <div style={{ marginTop: "15px", paddingTop: "15px", borderTop: "1px solid #333" }}>
1049
- <h4>Upload Knowledge Base</h4>
1050
- <p style={{ fontSize: "0.85em", color: "#888" }}>
1051
- Upload a .pl Prolog file (session-scoped)
1052
- </p>
1053
- <input
1054
- type="file"
1055
- accept=".pl"
1056
- onChange={handleFileUpload}
1057
- style={{ marginTop: "10px", marginBottom: "10px", width: "100%" }}
1058
- />
1059
- {uploadStatus && (
1060
- <div className="status-message">{uploadStatus}</div>
1061
- )}
1062
- </div>
1063
- {/* Ingest Documents Section */}
1064
- <div style={{ marginTop: "15px", paddingTop: "15px", borderTop: "1px solid #333" }}>
1065
- <h4>Ingest Documents</h4>
1066
- <input
1067
- type="text"
1068
- placeholder="arXiv id or URL (e.g., 1706.03762)"
1069
- value={arxivIdInput}
1070
- onChange={(e) => setArxivIdInput(e.target.value)}
1071
- style={{ width: "100%", marginTop: "10px" }}
1072
- />
1073
- <button
1074
- className="btn-secondary"
1075
- onClick={handleIngestArxiv}
1076
- style={{ marginTop: "10px", width: "100%" }}
1077
- disabled={sessionPanelLoading}
1078
- >
1079
- Ingest arXiv Paper
1080
- </button>
1081
- <input
1082
- type="text"
1083
- placeholder="Story URL (e.g., Project Gutenberg .txt)"
1084
- value={storyUrlInput}
1085
- onChange={(e) => setStoryUrlInput(e.target.value)}
1086
- style={{ width: "100%", marginTop: "10px" }}
1087
- />
1088
- <button
1089
- className="btn-secondary"
1090
- onClick={handleIngestStory}
1091
- style={{ marginTop: "10px", width: "100%" }}
1092
- disabled={sessionPanelLoading}
1093
- >
1094
- Ingest Story
1095
- </button>
1096
- </div>
1097
- {/* Session Actions */}
1098
- <div style={{ marginTop: "15px", paddingTop: "15px", borderTop: "1px solid #333" }}>
1099
- <h4>Session Actions</h4>
1100
- <button
1101
- className="btn-secondary"
1102
- onClick={refreshSessionMemory}
1103
- style={{ marginTop: "10px", width: "100%" }}
1104
- disabled={sessionPanelLoading}
1105
- >
1106
- 🔄 Refresh
1107
- </button>
1108
- <button
1109
- className="btn-secondary"
1110
- onClick={handleLoadMetadata}
1111
- style={{ marginTop: "10px", width: "100%" }}
1112
- >
1113
- Refresh KB Metadata
1114
- </button>
1115
- <button
1116
- className="btn-secondary"
1117
- onClick={handleDiscoverAndStage}
1118
- style={{ marginTop: "10px", width: "100%" }}
1119
- disabled={sessionPanelLoading}
1120
- >
1121
- Discover (Math) & Stage
1122
- </button>
1123
- <button
1124
- className="btn-secondary"
1125
- onClick={handleClearSessionMemory}
1126
- style={{ marginTop: "10px", width: "100%" }}
1127
- disabled={sessionPanelLoading}
1128
- >
1129
- Clear Session
1130
- </button>
1131
- <button
1132
- className="btn-secondary"
1133
- onClick={handleExportSessionMemory}
1134
- style={{ marginTop: "10px", width: "100%" }}
1135
- disabled={sessionPanelLoading}
1136
- >
1137
- Export Learned Lemmas
1138
- </button>
1139
- <button
1140
- className="btn-secondary"
1141
- onClick={handlePromoteSessionMemory}
1142
- style={{ marginTop: "10px", width: "100%" }}
1143
- disabled={sessionPanelLoading}
1144
- >
1145
- Promote (Bench-Gated)
1146
- </button>
1147
- <button
1148
- className="btn-secondary"
1149
- onClick={handleRollbackPromotion}
1150
- style={{ marginTop: "10px", width: "100%" }}
1151
- disabled={sessionPanelLoading}
1152
- >
1153
- Rollback Last Promotion
1154
- </button>
1155
- </div>
1156
-
1157
- {/* Display Areas */}
1158
- <div style={{ marginTop: "15px", paddingTop: "15px", borderTop: "1px solid #333" }}>
1159
- <h4>KB Metadata</h4>
1160
- {kbMetadata && (
1161
- <div className="metadata-panel">
1162
- <div>
1163
- <strong>Domain:</strong> {kbMetadata.domain_name || "Unknown"}
1164
- </div>
1165
- <div>
1166
- <strong>Domains:</strong> {(kbMetadata.domains || []).length}
1167
- </div>
1168
- <div>
1169
- <strong>Predicates:</strong> {(kbMetadata.predicates || []).length}
1170
- </div>
1171
- <div>
1172
- <strong>Relations:</strong> {(kbMetadata.relations || []).length}
1173
- </div>
1174
- <div>
1175
- <strong>Queryable:</strong> {(kbMetadata.queryable_predicates || []).length}
1176
- </div>
1177
- <details style={{ marginTop: "10px" }}>
1178
- <summary style={{ cursor: "pointer", fontWeight: "bold" }}>
1179
- Full Metadata
1180
- </summary>
1181
- <pre style={{ fontSize: "0.75em", overflowX: "auto", marginTop: "5px" }}>
1182
- {JSON.stringify(kbMetadata, null, 2)}
1183
- </pre>
1184
- </details>
1185
- </div>
1186
- )}
1187
- </div>
1188
-
1189
- {sessionPanelStatus && (
1190
- <div className="status-message" style={{ marginTop: "10px" }}>
1191
- {sessionPanelStatus}
1192
- </div>
1193
- )}
1194
- <div className="query-results" style={{ marginTop: "15px" }}>
1195
- <h4>Staged lemmas ({(sessionLemmas || []).length})</h4>
1196
- <pre style={{ fontSize: "0.85em", overflowX: "auto" }}>
1197
- {JSON.stringify(sessionLemmas || [], null, 2)}
1198
- </pre>
1199
- </div>
1200
- <div className="query-results" style={{ marginTop: "15px" }}>
1201
- <h4>Staged docs</h4>
1202
- <pre style={{ fontSize: "0.85em", overflowX: "auto" }}>
1203
- {JSON.stringify(sessionDocs || { papers: [], stories: [] }, null, 2)}
1204
- </pre>
1205
- </div>
1206
- </aside>
1207
- )}
1208
- </div>
1209
- </div>
1210
- );
1211
- }
1212
-
1213
- // ============================================================
1214
- // MESSAGE COMPONENT
1215
- // ============================================================
1216
-
1217
- function Message({ message }) {
1218
- const isUser = message.role === "user";
1219
- const [showDebug, setShowDebug] = useState(false);
1220
- const stripMarkdownFences = React.useCallback((text) => {
1221
- if (typeof text !== "string") return "";
1222
- // Remove triple-backtick fences like ```json ... ``` (common in LLM outputs).
1223
- return text
1224
- .replace(/```\s*json\s*/gi, "")
1225
- .replace(/```/g, "")
1226
- .trim();
1227
- }, []);
1228
-
1229
- // Show thinking animation if: no text yet OR if thinking flag is true with statusText
1230
- const isThinking = !isUser && message.thinking && ((!message.text || !message.text.trim()) || message.statusText);
1231
-
1232
- const displayText = React.useMemo(() => {
1233
- const raw = typeof message.text === "string" ? message.text : "";
1234
- return raw;
1235
- }, [message.text]);
1236
-
1237
- const normalizedText = React.useMemo(
1238
- () => normalizeLatex(displayText),
1239
- [displayText]
1240
- );
1241
-
1242
- return (
1243
- <div className={`message ${isUser ? "user" : "assistant"}`}>
1244
- <div className="bubble">
1245
- {isThinking && (
1246
- <div className="thinking-container">
1247
- <div className="thinking-dots">
1248
- <span></span>
1249
- <span></span>
1250
- <span></span>
1251
- </div>
1252
- {message.statusText && (
1253
- <div className="thinking-status">{message.statusText}</div>
1254
- )}
1255
- </div>
1256
- )}
1257
- {!isThinking && (
1258
- <ReactMarkdown
1259
- className="markdown-body"
1260
- remarkPlugins={[remarkMath, remarkGfm]}
1261
- rehypePlugins={[[rehypeKatex, { strict: "ignore", throwOnError: false, trust: true }]]}
1262
- skipHtml={false}
1263
- breaks={true}
1264
- >
1265
- {normalizedText}
1266
- </ReactMarkdown>
1267
- )}
1268
  </div>
1269
- {!isUser && message.loadingDebug && (
1270
- <div style={{
1271
- display: 'flex',
1272
- alignItems: 'center',
1273
- gap: '8px',
1274
- marginTop: '8px',
1275
- color: '#888',
1276
- fontSize: '0.9em'
1277
- }}>
1278
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ animation: "spin 1s linear infinite" }}>
1279
- <path d="M21 12a9 9 0 1 1-6.219-8.56"/>
1280
- </svg>
1281
- <span>Loading debug info...</span>
1282
- </div>
1283
- )}
1284
- {!isUser && message.debug && (
1285
- <>
1286
- <button
1287
- className="debug-toggle"
1288
- onClick={() => setShowDebug((v) => !v)}
1289
- style={{
1290
- marginTop: "8px",
1291
- fontSize: "0.85em",
1292
- padding: "4px 10px",
1293
- background: "#f0f0f0",
1294
- border: "1px solid #ccc",
1295
- borderRadius: "4px",
1296
- cursor: "pointer"
1297
- }}
1298
- >
1299
- {showDebug ? "Hide Prolog Queries" : "Show Prolog Queries"}
1300
- </button>
1301
- {showDebug && (
1302
- <div className="debug-panel" style={{
1303
- marginTop: "10px",
1304
- padding: "12px",
1305
- background: "#f8f8f8",
1306
- border: "1px solid #ddd",
1307
- borderRadius: "6px",
1308
- fontSize: "0.9em",
1309
- color: "#1a1a1a"
1310
- }}>
1311
- <h4 style={{ marginTop: 0, marginBottom: "10px", color: "#1a1a1a" }}>Prolog Query Analysis</h4>
1312
-
1313
- {message.debug.llm_analysis && (
1314
- <DebugExpander title="Generated Queries" defaultOpen={false}>
1315
- <pre style={{
1316
- background: "#fff",
1317
- padding: "8px",
1318
- borderRadius: "4px",
1319
- fontSize: "0.9em",
1320
- overflowX: "auto",
1321
- color: "#1a1a1a",
1322
- margin: 0
1323
- }}>
1324
- {stripMarkdownFences(message.debug.llm_analysis)}
1325
- </pre>
1326
- </DebugExpander>
1327
- )}
1328
-
1329
- {message.debug.predicates_queried && message.debug.predicates_queried.length > 0 && (
1330
- <DebugExpander title={`Predicates Queried (${message.debug.predicates_queried.length})`} defaultOpen={false}>
1331
- <span style={{ color: "#0066cc", fontWeight: "500" }}>
1332
- {message.debug.predicates_queried.join(", ")}
1333
- </span>
1334
- </DebugExpander>
1335
- )}
1336
-
1337
- {Array.isArray(message.debug.dropped_calls) && message.debug.dropped_calls.length > 0 && (
1338
- <DebugExpander title={`Dropped Tool Calls (${message.debug.dropped_calls.length})`} defaultOpen={false}>
1339
- <pre style={{
1340
- background: "#fff",
1341
- padding: "8px",
1342
- borderRadius: "4px",
1343
- fontSize: "0.85em",
1344
- overflowX: "auto",
1345
- color: "#1a1a1a",
1346
- border: "1px solid #e2e2e2",
1347
- margin: 0
1348
- }}>
1349
- {JSON.stringify(message.debug.dropped_calls, null, 2)}
1350
- </pre>
1351
- </DebugExpander>
1352
- )}
1353
-
1354
- {Array.isArray(message.debug.tool_calls_proof_retry) && message.debug.tool_calls_proof_retry.length > 0 && (
1355
- <DebugExpander title={`Proof Retry Tool Calls (${message.debug.tool_calls_proof_retry.length})`} defaultOpen={false}>
1356
- <pre style={{
1357
- background: "#fff",
1358
- padding: "8px",
1359
- borderRadius: "4px",
1360
- fontSize: "0.85em",
1361
- overflowX: "auto",
1362
- color: "#1a1a1a",
1363
- border: "1px solid #e2e2e2",
1364
- margin: 0
1365
- }}>
1366
- {JSON.stringify(message.debug.tool_calls_proof_retry, null, 2)}
1367
- </pre>
1368
- </DebugExpander>
1369
- )}
1370
-
1371
- {message.debug.predicate_docs && message.debug.predicate_docs.length > 0 && (
1372
- <DebugExpander title={`Predicate Descriptions (${message.debug.predicate_docs.length})`} defaultOpen={false}>
1373
- <ul style={{ marginTop: "8px", paddingLeft: "20px", color: "#1a1a1a", marginBottom: 0 }}>
1374
- {message.debug.predicate_docs.map((p, idx) => {
1375
- const sig = p && (p.signature || p.predicate) ? String(p.signature || p.predicate) : "";
1376
- const doc = p && p.doc ? String(p.doc) : "";
1377
- const usage = p && p.usage ? String(p.usage) : "";
1378
- const latex = p && p.latex ? String(p.latex) : "";
1379
- const md = [
1380
- sig ? `**${sig}**` : "**(unknown)**",
1381
- doc ? doc : "",
1382
- usage ? `Usage: \`${usage}\`` : "",
1383
- latex ? `LaTeX: $$${latex}$$` : "",
1384
- ]
1385
- .filter(Boolean)
1386
- .join("\n\n");
1387
- return (
1388
- <li key={idx} style={{ marginBottom: "10px" }}>
1389
- <div style={{ background: "#fff", border: "1px solid #e2e2e2", borderRadius: "4px", padding: "8px" }}>
1390
- <ReactMarkdown
1391
- remarkPlugins={[remarkMath]}
1392
- rehypePlugins={[[rehypeKatex, { strict: "ignore", throwOnError: false, trust: true }]]}
1393
- >
1394
- {md}
1395
- </ReactMarkdown>
1396
- </div>
1397
- </li>
1398
- );
1399
- })}
1400
- </ul>
1401
- </DebugExpander>
1402
- )}
1403
-
1404
- {message.debug.queries_executed && message.debug.queries_executed.length > 0 && (
1405
- <DebugExpander title={`Executed Queries (${message.debug.queries_executed.length})`} defaultOpen={false}>
1406
- <ul style={{ marginTop: "5px", paddingLeft: "20px", color: "#1a1a1a", marginBottom: 0 }}>
1407
- {message.debug.queries_executed.map((q, idx) => (
1408
- <li key={idx} style={{ marginBottom: "5px" }}>
1409
- <code style={{
1410
- background: "#e8f4f8",
1411
- padding: "2px 6px",
1412
- borderRadius: "3px",
1413
- fontSize: "0.9em",
1414
- color: "#1a1a1a"
1415
- }}>
1416
- {q.query}
1417
- </code>{" "}
1418
- <span style={{ color: "#333" }}>
1419
- → {q.results_count} result{q.results_count !== 1 ? "s" : ""}
1420
- </span>
1421
- </li>
1422
- ))}
1423
- </ul>
1424
- </DebugExpander>
1425
- )}
1426
-
1427
- {message.debug.evidence && (
1428
- <DebugExpander title={`Evidence (${(message.debug.evidence.facts || []).length} facts)`} defaultOpen={false}>
1429
- <div style={{ color: "#1a1a1a" }}>
1430
- {message.debug.evidence.fact_bindings && (
1431
- <div style={{ marginBottom: "10px" }}>
1432
- <strong>Structured bindings:</strong>{" "}
1433
- <span style={{ fontWeight: "bold" }}>
1434
- {(message.debug.evidence.fact_bindings || []).length}
1435
- </span>
1436
- {(message.debug.evidence.fact_bindings || []).length > 0 ? (
1437
- <pre style={{
1438
- background: "#fff",
1439
- padding: "8px",
1440
- borderRadius: "4px",
1441
- fontSize: "0.85em",
1442
- overflowX: "auto",
1443
- marginTop: "6px",
1444
- color: "#1a1a1a"
1445
- }}>
1446
- {JSON.stringify((message.debug.evidence.fact_bindings || []), null, 2)}
1447
- </pre>
1448
- ) : null}
1449
- </div>
1450
- )}
1451
- {/* Always show citations status, even if empty */}
1452
- <div style={{ marginTop: "8px" }}>
1453
- <div style={{ fontWeight: "600" }}>
1454
- Citations: {message.debug.evidence.citations ? message.debug.evidence.citations.length : 0}
1455
- </div>
1456
- {message.debug.evidence.citations && message.debug.evidence.citations.length > 0 ? (
1457
- <ul style={{ marginTop: "5px", paddingLeft: "20px" }}>
1458
- {message.debug.evidence.citations.map((c, idx) => (
1459
- <li key={idx} style={{ marginBottom: "4px" }}>
1460
- <span style={{ color: "#0066cc", fontWeight: "600" }}>[{c.fact_index}]</span>
1461
- {(() => {
1462
- const facts = message.debug.evidence.facts || [];
1463
- const i = typeof c.fact_index === "number" ? c.fact_index : Number(c.fact_index);
1464
- const factText = Number.isFinite(i) && i >= 0 && i < facts.length ? facts[i] : null;
1465
- return (
1466
- <>
1467
- {factText ? (
1468
- <span style={{ marginLeft: "8px", color: "#1a1a1a" }}>{String(factText)}</span>
1469
- ) : (
1470
- <span style={{ marginLeft: "8px", color: "#aa0000" }}>(missing fact)</span>
1471
- )}
1472
- {c.why ? <span style={{ marginLeft: "6px", color: "#333" }}>— {c.why}</span> : null}
1473
- </>
1474
- );
1475
- })()}
1476
- </li>
1477
- ))}
1478
- </ul>
1479
- ) : (
1480
- <div style={{ color: "#666", fontSize: "0.9em", marginTop: "4px" }}>
1481
- (No citation markers [0], [1], [2]... found in response)
1482
- </div>
1483
- )}
1484
- </div>
1485
- {message.debug.evidence.obligations && (
1486
- <div style={{ marginTop: "8px" }}>
1487
- <div style={{ fontWeight: "600" }}>Proof obligations:</div>
1488
- <div style={{ color: "#333" }}>
1489
- Valid citations: {message.debug.evidence.obligations.valid_citations || 0}
1490
- {message.debug.evidence.obligations.invalid_citations && message.debug.evidence.obligations.invalid_citations.length > 0 ? (
1491
- <span style={{ marginLeft: "8px", color: "#aa0000", fontWeight: "600" }}>
1492
- Invalid: {message.debug.evidence.obligations.invalid_citations.length}
1493
- </span>
1494
- ) : null}
1495
- </div>
1496
- </div>
1497
- )}
1498
- </div>
1499
- </DebugExpander>
1500
- )}
1501
-
1502
- <div style={{ marginTop: "10px", paddingTop: "10px", borderTop: "1px solid #ddd" }}>
1503
- <strong style={{ color: "#1a1a1a" }}>Total Results:</strong>{" "}
1504
- <span style={{ color: "#00aa00", fontWeight: "bold" }}>
1505
- {message.debug.total_results || 0}
1506
- </span>
1507
- </div>
1508
- </div>
1509
- )}
1510
- </>
1511
- )}
1512
  </div>
1513
  );
1514
  }
1515
 
1516
-
1517
- export default App;
 
1
  // src/App.js
2
 
3
+ import React, { useState, useMemo } from "react";
4
+ import { login, streamChat } from "./api";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  import "./App.css";
6
 
7
  import ReactMarkdown from "react-markdown";
8
  import remarkMath from "remark-math";
9
  import rehypeKatex from "rehype-katex";
10
  import "katex/dist/katex.min.css";
 
11
  import remarkGfm from "remark-gfm";
12
 
13
+ // ---------------------------------------------------------------------------
14
+ // QUOTES
15
+ // ---------------------------------------------------------------------------
16
  const LOGIC_SAYINGS = [
17
  "Logic is the compass; reason is the journey.",
18
+ "Logic doesn\u2019t tell you where to go\u2014only how not to get lost.",
19
  "Emotion starts the fire; logic builds the fireplace.",
20
  "Logic is truth with the noise removed.",
21
  "Where logic ends, belief begins.",
 
27
  "Logic is thinking that survives inspection.",
28
  "Feelings persuade; logic convinces.",
29
  "Logic is the skeleton beneath every solid idea.",
 
30
  "Logic is humility formalized.",
31
+ "Logic is the courage to follow conclusions you don\u2019t like.",
32
  "Logic is what remains when excuses are removed.",
 
33
  "Logic is slow thinking that wins.",
34
  "Logic is the art of necessary consequences.",
35
+ "Logic is not cold\u2014it\u2019s honest.",
36
+ "Logic asks \u2018must it be so?\u2019",
 
37
  "Logic is the bridge between assumptions and reality.",
38
  "Logic is doubt with a method.",
39
  "Logic is reason refusing shortcuts.",
 
 
40
  "Logic is clarity earned, not assumed.",
 
 
 
 
 
41
  "Logic is the enemy of convenient nonsense.",
 
42
  "Logic is freedom from contradiction.",
43
+ "Logic is the courage to say \u2018I was wrong.\u2019",
 
 
44
  "Logic is precision applied to belief.",
 
45
  "Logic is the difference between opinion and argument.",
 
46
  "Logic is trust in structure over impulse.",
 
47
  "Logic is thought that can be audited.",
48
  "Logic is the firewall against self-deception.",
 
 
 
 
 
 
 
49
  "Logic is truth, step by step.",
 
 
50
  "Logic is thinking that welcomes scrutiny.",
 
51
  "Logic is the difference between sounding right and being right.",
 
 
52
  "Logic is belief with a warranty.",
 
53
  "Logic is calm thinking in loud situations.",
 
 
 
54
  "Logic is the architecture of understanding.",
 
 
 
55
  "Logic is the slow weapon against fast lies.",
56
  "Logic is consistency made explicit.",
57
+ "Logic is explanation that doesn\u2019t flinch.",
 
 
 
58
  "Logic is truth under constraints.",
 
59
  "Logic is evidence wearing syntax.",
60
  "Logic is the guardrail of intelligence.",
 
61
  "Logic is the art of unavoidable conclusions.",
 
62
  "Logic is reasoning that respects reality.",
 
63
  "Logic is the structure beneath insight.",
 
 
 
 
64
  "Logic is understanding without shortcuts.",
 
65
  "Logic is thought with integrity.",
 
66
  "Logic is the science of consistency.",
67
+ "Logic is respect\u2014for truth, for thought, and for consequence.",
 
68
  ];
69
 
70
+ // ---------------------------------------------------------------------------
71
+ // HELPERS
72
+ // ---------------------------------------------------------------------------
73
  function normalizeLatex(text) {
74
  if (!text) return "";
75
+ let n = text;
76
+ n = n.replace(/\\\[(.+?)\\\]/gs, (_, i) => `$$${i}$$`);
77
+ n = n.replace(/\\\((.+?)\\\)/gs, (_, i) => `$${i}$`);
78
+ n = n.replace(/\$\$\$\$/g, "$$");
79
+ n = n.replace(/\$\$\$/g, "$$");
80
+ n = n.replace(/\\begin\{align\*?\}/g, "\\begin{aligned}");
81
+ n = n.replace(/\\end\{align\*?\}/g, "\\end{aligned}");
82
+ n = n.replace(/\\begin\{equation\*?\}/g, "");
83
+ n = n.replace(/\\end\{equation\*?\}/g, "");
84
+ n = n.replace(/\\begin\{gather\*?\}/g, "\\begin{gathered}");
85
+ n = n.replace(/\\end\{gather\*?\}/g, "\\end{gathered}");
86
+ n = n.replace(/\\begin\{eqnarray\*?\}/g, "\\begin{aligned}");
87
+ n = n.replace(/\\end\{eqnarray\*?\}/g, "\\end{aligned}");
88
+ n = n.replace(/\$\$([^$]+?)\$\$/gs, (match, inner) => {
89
+ const t = inner.trim();
90
+ const hasAlign = /[^\\]&/.test(t) || t.startsWith("&");
91
+ const hasEnv = /\\begin\{/.test(t);
92
+ if (hasAlign && !hasEnv) return `$$\\begin{aligned}\n${t}\n\\end{aligned}$$`;
93
+ return `$$${t}$$`;
 
 
 
 
 
 
 
 
 
 
94
  });
95
+ return n;
 
96
  }
97
 
98
+ // ---------------------------------------------------------------------------
99
+ // COLLAPSIBLE DEBUG SECTION
100
+ // ---------------------------------------------------------------------------
101
  function DebugExpander({ title, defaultOpen = false, children }) {
102
+ const [open, setOpen] = useState(defaultOpen);
 
103
  return (
104
+ <div style={{ marginBottom: 12 }}>
105
  <button
106
+ onClick={() => setOpen(!open)}
107
  style={{
108
+ width: "100%", textAlign: "left", padding: "8px 12px",
109
+ background: open ? "#e8f4f8" : "#fff", border: "1px solid #ccc",
110
+ borderRadius: 4, cursor: "pointer", display: "flex",
111
+ alignItems: "center", justifyContent: "space-between",
112
+ fontWeight: 600, color: "#1a1a1a", fontSize: "0.9em",
 
 
 
 
 
 
 
 
113
  }}
114
  >
115
  <span>{title}</span>
116
+ <span style={{ fontSize: "1.2em", transform: open ? "rotate(90deg)" : "rotate(0deg)", transition: "transform 0.2s", display: "inline-block" }}>&#9654;</span>
 
 
 
 
 
 
 
117
  </button>
118
+ {open && (
119
+ <div style={{ marginTop: 8, padding: 10, background: "#fff", border: "1px solid #e2e2e2", borderRadius: 4 }}>
 
 
 
 
 
 
120
  {children}
121
  </div>
122
  )}
 
124
  );
125
  }
126
 
127
+ // ---------------------------------------------------------------------------
128
+ // MESSAGE BUBBLE
129
+ // ---------------------------------------------------------------------------
130
+ function Message({ message }) {
131
+ const isUser = message.role === "user";
132
+ const [showDebug, setShowDebug] = useState(false);
 
133
 
134
+ const stripFences = React.useCallback((t) => {
135
+ if (typeof t !== "string") return "";
136
+ return t.replace(/```\s*json\s*/gi, "").replace(/```/g, "").trim();
137
+ }, []);
 
 
 
 
 
 
138
 
139
+ const isThinking =
140
+ !isUser && message.thinking && (!message.text?.trim() || message.statusText);
 
141
 
142
+ const normalizedText = useMemo(
143
+ () => normalizeLatex(message.text || ""),
144
+ [message.text]
145
+ );
146
 
147
+ return (
148
+ <div className={`message ${isUser ? "user" : "assistant"}`}>
149
+ <div className="bubble">
150
+ {isThinking ? (
151
+ <div className="thinking-container">
152
+ <div className="thinking-dots"><span /><span /><span /></div>
153
+ {message.statusText && <div className="thinking-status">{message.statusText}</div>}
154
+ </div>
155
+ ) : (
156
+ <ReactMarkdown
157
+ className="markdown-body"
158
+ remarkPlugins={[remarkMath, remarkGfm]}
159
+ rehypePlugins={[[rehypeKatex, { strict: "ignore", throwOnError: false, trust: true, errorColor: "#e2e8f0" }]]}
160
+ skipHtml={false}
161
+ breaks
162
+ >
163
+ {normalizedText}
164
+ </ReactMarkdown>
165
+ )}
166
+ </div>
167
 
168
+ {/* Debug panel */}
169
+ {!isUser && message.debug && (
170
+ <>
171
+ <button
172
+ className="debug-toggle"
173
+ onClick={() => setShowDebug((v) => !v)}
174
+ style={{ marginTop: 8, fontSize: "0.85em", padding: "4px 10px", background: "#f0f0f0", border: "1px solid #ccc", borderRadius: 4, cursor: "pointer" }}
175
+ >
176
+ {showDebug ? "Hide Prolog Queries" : "Show Prolog Queries"}
177
+ </button>
178
+ {showDebug && (
179
+ <div className="debug-panel" style={{ marginTop: 10, padding: 12, background: "#f8f8f8", border: "1px solid #ddd", borderRadius: 6, fontSize: "0.9em", color: "#1a1a1a" }}>
180
+ <h4 style={{ marginTop: 0, marginBottom: 10 }}>Prolog Query Analysis</h4>
181
 
182
+ {message.debug.llm_analysis && (
183
+ <DebugExpander title="Generated Queries">
184
+ <pre style={{ background: "#fff", padding: 8, borderRadius: 4, fontSize: "0.9em", overflowX: "auto", color: "#1a1a1a", margin: 0 }}>
185
+ {stripFences(message.debug.llm_analysis)}
186
+ </pre>
187
+ </DebugExpander>
188
+ )}
 
 
 
 
 
 
 
 
 
 
 
189
 
190
+ {message.debug.predicates_queried?.length > 0 && (
191
+ <DebugExpander title={`Predicates Queried (${message.debug.predicates_queried.length})`}>
192
+ <span style={{ color: "#0066cc", fontWeight: 500 }}>
193
+ {message.debug.predicates_queried.join(", ")}
194
+ </span>
195
+ </DebugExpander>
196
+ )}
 
 
197
 
198
+ {message.debug.queries_executed?.length > 0 && (
199
+ <DebugExpander title={`Executed Queries (${message.debug.queries_executed.length})`}>
200
+ <ul style={{ marginTop: 5, paddingLeft: 20, marginBottom: 0 }}>
201
+ {message.debug.queries_executed.map((q, i) => (
202
+ <li key={i} style={{ marginBottom: 5 }}>
203
+ <code style={{ background: "#e8f4f8", padding: "2px 6px", borderRadius: 3, fontSize: "0.9em" }}>{q.query}</code>{" "}
204
+ <span style={{ color: "#333" }}>{"\u2192"} {q.results_count} result{q.results_count !== 1 ? "s" : ""}</span>
205
+ </li>
206
+ ))}
207
+ </ul>
208
+ </DebugExpander>
209
+ )}
210
 
211
+ {message.debug.evidence && (
212
+ <DebugExpander title={`Evidence (${(message.debug.evidence.facts || []).length} facts)`}>
213
+ <div>
214
+ {message.debug.evidence.fact_bindings?.length > 0 && (
215
+ <div style={{ marginBottom: 10 }}>
216
+ <strong>Structured bindings:</strong> {message.debug.evidence.fact_bindings.length}
217
+ <pre style={{ background: "#fff", padding: 8, borderRadius: 4, fontSize: "0.85em", overflowX: "auto", marginTop: 6 }}>
218
+ {JSON.stringify(message.debug.evidence.fact_bindings, null, 2)}
219
+ </pre>
220
+ </div>
221
+ )}
222
+ </div>
223
+ </DebugExpander>
224
+ )}
225
 
226
+ <div style={{ marginTop: 10, paddingTop: 10, borderTop: "1px solid #ddd" }}>
227
+ <strong>Total Results:</strong>{" "}
228
+ <span style={{ color: "#00aa00", fontWeight: "bold" }}>{message.debug.total_results || 0}</span>
229
+ </div>
230
+ </div>
231
+ )}
232
+ </>
233
+ )}
234
+ </div>
235
+ );
236
+ }
237
 
238
+ // ---------------------------------------------------------------------------
239
+ // MAIN APP
240
+ // ---------------------------------------------------------------------------
241
+ function App() {
242
+ const randomSaying = useMemo(
243
+ () => LOGIC_SAYINGS[Math.floor(Math.random() * LOGIC_SAYINGS.length)],
244
+ []
245
+ );
246
 
247
+ // Auth
248
+ const [token, setToken] = useState(null);
249
+ const [authError, setAuthError] = useState(null);
250
+ const [loginForm, setLoginForm] = useState({ username: "", password: "" });
251
 
252
+ // Chat
253
+ const [messages, setMessages] = useState([]);
254
+ const [input, setInput] = useState("");
255
+ const [loading, setLoading] = useState(false);
256
+ const [error, setError] = useState(null);
 
 
257
 
258
+ // Session trigger for new chat
259
+ const [sessionTrigger, setSessionTrigger] = useState(0);
260
+ const sessionId = useMemo(() => {
261
+ try { return crypto.randomUUID(); } catch {}
262
+ return `sid-${Date.now()}-${Math.random().toString(16).slice(2)}`;
263
+ }, [sessionTrigger]); // eslint-disable-line react-hooks/exhaustive-deps
264
 
265
+ // Auto-scroll
 
 
266
  React.useEffect(() => {
267
+ const c = document.querySelector(".messages");
268
+ if (c) c.scrollTop = c.scrollHeight;
269
+ }, [messages]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
 
271
+ // ── Login ──
 
 
272
  async function handleLogin(e) {
273
  e.preventDefault();
274
  setAuthError(null);
 
275
  try {
276
  const res = await login(loginForm.username, loginForm.password);
277
+ setToken(res.token);
 
278
  } catch (err) {
279
  setAuthError(err.message || "Login failed");
280
  }
281
  }
282
 
283
+ // ── New chat ──
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284
  function handleNewChat() {
285
  setMessages([]);
286
  setInput("");
287
  setError(null);
288
+ setSessionTrigger((p) => p + 1);
 
 
 
 
289
  }
290
 
291
+ // ── Send message + stream response ──
 
 
292
  async function handleSend(e) {
293
  if (e) e.preventDefault();
294
  if (!input.trim() || loading || !token) return;
295
 
296
  const userMsg = { role: "user", text: input.trim() };
297
+ const assistantMsg = { role: "assistant", text: "", debug: null, thinking: true, statusText: "" };
298
+ const newMessages = [...messages, userMsg, assistantMsg];
 
 
 
 
 
299
  setMessages(newMessages);
300
  setInput("");
301
  setError(null);
302
  setLoading(true);
 
303
 
304
  try {
305
+ const history = newMessages.map((m) => ({ role: m.role, content: m.text }));
 
 
 
 
 
 
 
 
306
  await streamChat(
307
  userMsg.text,
308
+ history,
 
309
  token,
310
  (chunk) => {
311
+ if (assistantMsg.thinking && !assistantMsg.text?.trim()) {
312
  assistantMsg.text = chunk;
313
  assistantMsg.thinking = false;
314
+ assistantMsg.statusText = "";
315
  } else {
316
+ assistantMsg.text += chunk;
317
  }
318
+ setMessages([...newMessages]);
319
  },
320
  sessionId,
321
  (statusMsg) => {
322
+ if (!assistantMsg.text?.trim()) {
 
323
  assistantMsg.statusText = statusMsg;
324
+ assistantMsg.thinking = true;
325
  setMessages([...newMessages]);
326
  }
327
  },
328
  (debugData) => {
 
 
329
  assistantMsg.debug = debugData;
 
330
  setMessages([...newMessages]);
331
  }
332
  );
 
 
333
  assistantMsg.thinking = false;
334
  assistantMsg.statusText = "";
 
335
  setMessages([...newMessages]);
 
336
  } catch (err) {
337
  assistantMsg.thinking = false;
338
  assistantMsg.text += `\n[Error: ${err.message}]`;
339
  setMessages([...newMessages]);
340
  } finally {
341
  setLoading(false);
 
342
  }
343
  }
344
 
345
+ // ── Login screen ──
 
 
 
346
  if (!token) {
347
  return (
348
  <div className="app-root">
 
352
  <main className="main login">
353
  <form className="login-form" onSubmit={handleLogin}>
354
  <h2>Sign In</h2>
355
+ <input type="text" placeholder="Username" value={loginForm.username}
356
+ onChange={(e) => setLoginForm({ ...loginForm, username: e.target.value })} />
357
+ <input type="password" placeholder="Password" value={loginForm.password}
358
+ onChange={(e) => setLoginForm({ ...loginForm, password: e.target.value })} />
 
 
 
 
 
 
 
 
 
 
 
 
359
  <button type="submit">Log In</button>
360
  {authError && <div className="error">{authError}</div>}
361
  </form>
 
364
  );
365
  }
366
 
367
+ // ── Chat UI ──
 
 
368
  return (
369
  <div className="app-root">
370
  <header className="header">
371
  <h1 className="header-title">Prolog AI</h1>
372
  <div className="header-actions">
373
+ <button className="btn-secondary" onClick={handleNewChat} title="New Chat Session">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
375
+ <path d="M12 5v14M5 12h14" />
 
376
  </svg>
377
  </button>
378
+ <button className="logout-btn" onClick={() => setToken(null)} title="Logout">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
379
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
380
+ <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
381
+ <polyline points="16 17 21 12 16 7" />
382
+ <line x1="21" y1="12" x2="9" y2="12" />
383
  </svg>
384
  </button>
385
  </div>
386
  </header>
387
+
388
  <div className="app-container">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
389
  <main className="main">
390
  <div className="messages">
391
  {messages.map((msg, idx) => (
 
399
  value={input}
400
  onChange={(e) => setInput(e.target.value)}
401
  onKeyDown={(e) => {
402
+ if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleSend(); }
 
 
 
403
  }}
404
  disabled={loading}
405
  rows="2"
406
  />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
407
  </form>
408
  </main>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
409
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
410
  </div>
411
  );
412
  }
413
 
414
+ export default App;
 
src/api.js CHANGED
@@ -10,77 +10,40 @@ export async function login(username, password) {
10
 
11
  let json;
12
  const text = await res.text().catch(() => "");
13
-
14
  try {
15
  json = text ? JSON.parse(text) : {};
16
  } catch {
17
  json = {};
18
  }
19
 
20
- // HTTP not OK
21
  if (!res.ok) {
22
- const msg =
23
- (json && json.error) ||
24
- text ||
25
- `Login failed with status ${res.status}`;
26
- throw new Error(msg);
27
  }
28
-
29
- // HTTP OK but backend says ok: false
30
  if (!json.ok || !json.token) {
31
- throw new Error(json.error || "Login failed");
32
  }
33
-
34
  return json; // { ok, token }
35
  }
36
 
37
-
38
- export async function sendChat(message, strictMode = true, history = [], token, sessionId = null) {
39
- const res = await fetch(`${API_BASE}/chat`, {
40
- method: "POST",
41
- headers: {
42
- "Content-Type": "application/json",
43
- Authorization: `Bearer ${token}`, // 🟢 send JWT
44
- },
45
- body: JSON.stringify({
46
- message,
47
- strict_mode: strictMode,
48
- history,
49
- session_id: sessionId,
50
- }),
51
- });
52
-
53
- if (!res.ok) {
54
- const text = await res.text().catch(() => "");
55
- throw new Error(`HTTP ${res.status}: ${text || "Request failed"}`);
56
- }
57
-
58
- const json = await res.json();
59
- if (!json.ok) {
60
- throw new Error(json.error || "Chat failed");
61
- }
62
-
63
- return json;
64
- }
65
-
66
- export async function streamChat(message, strictMode, history, token, onToken, sessionId = null, onStatus = null, onDebug = null) {
67
  const res = await fetch(`${API_BASE}/chat/stream`, {
68
  method: "POST",
69
  headers: {
70
  "Content-Type": "application/json",
71
- "Authorization": `Bearer ${token}`
72
  },
73
- body: JSON.stringify({
74
- message,
75
- strict_mode: strictMode,
76
- history,
77
- session_id: sessionId,
78
- }),
79
  });
80
 
81
- if (!res.body) {
82
- throw new Error("Streaming not supported by server");
83
- }
84
 
85
  const reader = res.body.getReader();
86
  const decoder = new TextDecoder();
@@ -90,70 +53,51 @@ export async function streamChat(message, strictMode, history, token, onToken, s
90
  const { value, done } = await reader.read();
91
  if (done) break;
92
 
93
- const chunk = decoder.decode(value);
94
- buffer += chunk;
95
 
96
- // Parse status messages: __STATUS__:{"message": "..."}__END__
97
- const statusRegex = /__STATUS__:(.*?)__END__/g;
98
- // Parse debug info: __DEBUG__:{...}__END__
99
- const debugRegex = /__DEBUG__:(.*?)__END__/g;
100
  let match;
101
  let lastIndex = 0;
102
 
103
- while ((match = statusRegex.exec(buffer)) !== null) {
104
- // Send any text before the status message as content
105
  if (match.index > lastIndex) {
106
  const content = buffer.substring(lastIndex, match.index);
107
  if (content) onToken(content);
108
  }
109
-
110
- // Parse and send status message
111
  try {
112
- const statusData = JSON.parse(match[1]);
113
- if (onStatus && statusData.message) {
114
- onStatus(statusData.message);
115
- }
116
- } catch (e) {
117
- console.error("Failed to parse status message:", match[1]);
118
- }
119
-
120
- lastIndex = statusRegex.lastIndex;
121
  }
122
-
123
- // Parse debug info
124
- debugRegex.lastIndex = 0; // Reset regex
125
- while ((match = debugRegex.exec(buffer)) !== null) {
126
  try {
127
- console.log("Debug marker found:", match[1].substring(0, 100));
128
- const debugData = JSON.parse(match[1]);
129
- console.log("Debug data parsed:", debugData);
130
- if (onDebug) {
131
- onDebug(debugData);
132
- }
133
- // Remove debug marker from buffer
134
- buffer = buffer.substring(0, match.index) + buffer.substring(debugRegex.lastIndex);
135
- debugRegex.lastIndex = match.index;
136
- } catch (e) {
137
- console.error("Failed to parse debug info:", match[1]);
138
- }
139
  }
140
 
141
- // Send remaining content
142
  if (lastIndex < buffer.length) {
143
  const content = buffer.substring(lastIndex);
144
- // Keep last part in buffer in case status/debug message is split across chunks
145
  if (!content.includes("__STATUS__") && !content.includes("__DEBUG__")) {
146
  onToken(content);
147
  buffer = "";
148
  } else {
149
- // Keep potential incomplete marker in buffer
150
- const lastMarkerStart = Math.max(
151
  content.lastIndexOf("__STATUS__"),
152
  content.lastIndexOf("__DEBUG__")
153
  );
154
- if (lastMarkerStart > 0) {
155
- onToken(content.substring(0, lastMarkerStart));
156
- buffer = content.substring(lastMarkerStart);
157
  } else {
158
  buffer = content;
159
  }
@@ -161,401 +105,8 @@ export async function streamChat(message, strictMode, history, token, onToken, s
161
  }
162
  }
163
 
164
- // Send any remaining buffer content
165
  if (buffer && !buffer.includes("__STATUS__") && !buffer.includes("__DEBUG__")) {
166
  onToken(buffer);
167
  }
168
  }
169
-
170
- export async function uploadPrologFile(prologCode, token) {
171
- const res = await fetch(`${API_BASE}/prolog/upload`, {
172
- method: "POST",
173
- headers: {
174
- "Content-Type": "application/json",
175
- Authorization: `Bearer ${token}`,
176
- },
177
- body: JSON.stringify({ prolog_code: prologCode }),
178
- });
179
-
180
- if (!res.ok) {
181
- const text = await res.text().catch(() => "");
182
- throw new Error(`HTTP ${res.status}: ${text || "Upload failed"}`);
183
- }
184
-
185
- const json = await res.json();
186
- if (!json.ok) {
187
- throw new Error(json.error || "Upload failed");
188
- }
189
-
190
- return json;
191
- }
192
-
193
-
194
- export async function discoverMath(question, token, sessionId = null, nLemmas = 5, maxSamples = 250, stage = true) {
195
- const res = await fetch(`${API_BASE}/math/discover`, {
196
- method: "POST",
197
- headers: {
198
- "Content-Type": "application/json",
199
- Authorization: `Bearer ${token}`,
200
- },
201
- body: JSON.stringify({
202
- question,
203
- n_lemmas: nLemmas,
204
- max_samples: maxSamples,
205
- session_id: sessionId,
206
- stage,
207
- }),
208
- });
209
-
210
- if (!res.ok) {
211
- const text = await res.text().catch(() => "");
212
- throw new Error(`HTTP ${res.status}: ${text || "Request failed"}`);
213
- }
214
-
215
- const json = await res.json();
216
- if (!json.ok) {
217
- throw new Error(json.error || "Math discovery failed");
218
- }
219
-
220
- return json;
221
- }
222
-
223
-
224
- export async function listSessionLemmas(sessionId, token) {
225
- const res = await fetch(`${API_BASE}/session/lemmas`, {
226
- method: "POST",
227
- headers: {
228
- "Content-Type": "application/json",
229
- Authorization: `Bearer ${token}`,
230
- },
231
- body: JSON.stringify({ session_id: sessionId }),
232
- });
233
-
234
- if (!res.ok) {
235
- const text = await res.text().catch(() => "");
236
- throw new Error(`HTTP ${res.status}: ${text || "Request failed"}`);
237
- }
238
-
239
- const json = await res.json();
240
- if (!json.ok) {
241
- throw new Error(json.error || "List session lemmas failed");
242
- }
243
-
244
- return json;
245
- }
246
-
247
-
248
- export async function listSessionDocs(sessionId, token) {
249
- const res = await fetch(`${API_BASE}/session/docs`, {
250
- method: "POST",
251
- headers: {
252
- "Content-Type": "application/json",
253
- Authorization: `Bearer ${token}`,
254
- },
255
- body: JSON.stringify({ session_id: sessionId }),
256
- });
257
-
258
- if (!res.ok) {
259
- const text = await res.text().catch(() => "");
260
- throw new Error(`HTTP ${res.status}: ${text || "Request failed"}`);
261
- }
262
-
263
- const json = await res.json();
264
- if (!json.ok) {
265
- throw new Error(json.error || "List session docs failed");
266
- }
267
-
268
- return json;
269
- }
270
-
271
-
272
- export async function clearSession(sessionId, token) {
273
- const res = await fetch(`${API_BASE}/session/clear`, {
274
- method: "POST",
275
- headers: {
276
- "Content-Type": "application/json",
277
- Authorization: `Bearer ${token}`,
278
- },
279
- body: JSON.stringify({ session_id: sessionId }),
280
- });
281
-
282
- if (!res.ok) {
283
- const text = await res.text().catch(() => "");
284
- throw new Error(`HTTP ${res.status}: ${text || "Request failed"}`);
285
- }
286
-
287
- const json = await res.json();
288
- if (!json.ok) {
289
- throw new Error(json.error || "Clear session failed");
290
- }
291
-
292
- return json;
293
- }
294
-
295
-
296
- export async function ingestArxivToSession(sessionId, token, arxivIdOrUrl, maxParagraphs = 200, skipMarkitdown = false) {
297
- const res = await fetch(`${API_BASE}/ingest/arxiv`, {
298
- method: "POST",
299
- headers: {
300
- "Content-Type": "application/json",
301
- Authorization: `Bearer ${token}`,
302
- },
303
- body: JSON.stringify({
304
- session_id: sessionId,
305
- arxiv_id: arxivIdOrUrl,
306
- max_paragraphs: maxParagraphs,
307
- skip_markitdown: skipMarkitdown,
308
- }),
309
- });
310
-
311
- if (!res.ok) {
312
- const text = await res.text().catch(() => "");
313
- throw new Error(`HTTP ${res.status}: ${text || "Request failed"}`);
314
- }
315
-
316
- const json = await res.json();
317
- if (!json.ok) {
318
- throw new Error(json.error || "Ingest arXiv failed");
319
- }
320
-
321
- return json;
322
- }
323
-
324
-
325
- export async function ingestStoryToSession(sessionId, token, url, storyId = "story", title = "", maxParagraphs = 200) {
326
- const res = await fetch(`${API_BASE}/ingest/story`, {
327
- method: "POST",
328
- headers: {
329
- "Content-Type": "application/json",
330
- Authorization: `Bearer ${token}`,
331
- },
332
- body: JSON.stringify({
333
- session_id: sessionId,
334
- url,
335
- story_id: storyId,
336
- title,
337
- max_paragraphs: maxParagraphs,
338
- }),
339
- });
340
-
341
- if (!res.ok) {
342
- const text = await res.text().catch(() => "");
343
- throw new Error(`HTTP ${res.status}: ${text || "Request failed"}`);
344
- }
345
-
346
- const json = await res.json();
347
- if (!json.ok) {
348
- throw new Error(json.error || "Ingest story failed");
349
- }
350
-
351
- return json;
352
- }
353
-
354
-
355
- export async function rollbackSessionPromotion(sessionId, token, deleteFile = false) {
356
- const res = await fetch(`${API_BASE}/session/rollback`, {
357
- method: "POST",
358
- headers: {
359
- "Content-Type": "application/json",
360
- Authorization: `Bearer ${token}`,
361
- },
362
- body: JSON.stringify({ session_id: sessionId, delete_file: deleteFile }),
363
- });
364
-
365
- if (!res.ok) {
366
- const text = await res.text().catch(() => "");
367
- throw new Error(`HTTP ${res.status}: ${text || "Request failed"}`);
368
- }
369
-
370
- const json = await res.json();
371
- if (!json.ok) {
372
- throw new Error(json.error || "Rollback failed");
373
- }
374
-
375
- return json;
376
- }
377
-
378
-
379
- export async function exportSessionLemmas(sessionId, token, note = null) {
380
- const res = await fetch(`${API_BASE}/session/export`, {
381
- method: "POST",
382
- headers: {
383
- "Content-Type": "application/json",
384
- Authorization: `Bearer ${token}`,
385
- },
386
- body: JSON.stringify({ session_id: sessionId, note }),
387
- });
388
-
389
- if (!res.ok) {
390
- const text = await res.text().catch(() => "");
391
- throw new Error(`HTTP ${res.status}: ${text || "Request failed"}`);
392
- }
393
-
394
- const json = await res.json();
395
- if (!json.ok) {
396
- throw new Error(json.error || "Export session lemmas failed");
397
- }
398
-
399
- return json;
400
- }
401
-
402
-
403
- export async function promoteSessionLemmas(sessionId, token, note = null, gateBenchmarks = true) {
404
- const res = await fetch(`${API_BASE}/session/promote`, {
405
- method: "POST",
406
- headers: {
407
- "Content-Type": "application/json",
408
- Authorization: `Bearer ${token}`,
409
- },
410
- body: JSON.stringify({
411
- session_id: sessionId,
412
- note,
413
- gate_benchmarks: gateBenchmarks,
414
- }),
415
- });
416
-
417
- if (!res.ok) {
418
- const text = await res.text().catch(() => "");
419
- throw new Error(`HTTP ${res.status}: ${text || "Request failed"}`);
420
- }
421
-
422
- const json = await res.json();
423
- if (!json.ok) {
424
- throw new Error(json.error || "Promote session lemmas failed");
425
- }
426
-
427
- return json;
428
- }
429
-
430
-
431
- export async function proveGoal(goal, token, maxDepth = 20, inferenceLimit = 50000) {
432
- const res = await fetch(`${API_BASE}/prolog/prove`, {
433
- method: "POST",
434
- headers: {
435
- "Content-Type": "application/json",
436
- Authorization: `Bearer ${token}`,
437
- },
438
- body: JSON.stringify({
439
- goal,
440
- max_depth: maxDepth,
441
- inference_limit: inferenceLimit,
442
- }),
443
- });
444
-
445
- if (!res.ok) {
446
- const text = await res.text().catch(() => "");
447
- throw new Error(`HTTP ${res.status}: ${text || "Request failed"}`);
448
- }
449
-
450
- const json = await res.json();
451
- if (!json.ok) {
452
- throw new Error(json.error || "Prove goal failed");
453
- }
454
-
455
- return json;
456
- }
457
-
458
- export async function getKBMetadata(token) {
459
- const res = await fetch(`${API_BASE}/prolog/metadata`, {
460
- method: "GET",
461
- headers: {
462
- Authorization: `Bearer ${token}`,
463
- },
464
- });
465
-
466
- if (!res.ok) {
467
- const text = await res.text().catch(() => "");
468
- throw new Error(`HTTP ${res.status}: ${text || "Metadata fetch failed"}`);
469
- }
470
-
471
- const json = await res.json();
472
- if (!json.ok) {
473
- throw new Error(json.error || "Metadata fetch failed");
474
- }
475
-
476
- return json;
477
- }
478
-
479
- export async function queryProlog(query, token, maxSolutions = 10) {
480
- const res = await fetch(`${API_BASE}/prolog/query`, {
481
- method: "POST",
482
- headers: {
483
- "Content-Type": "application/json",
484
- Authorization: `Bearer ${token}`,
485
- },
486
- body: JSON.stringify({ query, max_solutions: maxSolutions }),
487
- });
488
-
489
- if (!res.ok) {
490
- const text = await res.text().catch(() => "");
491
- throw new Error(`HTTP ${res.status}: ${text || "Query failed"}`);
492
- }
493
-
494
- const json = await res.json();
495
- if (!json.ok) {
496
- throw new Error(json.error || "Query failed");
497
- }
498
-
499
- return json;
500
- }
501
-
502
-
503
- export async function getMe(token) {
504
- const res = await fetch(`${API_BASE}/me`, {
505
- method: "GET",
506
- headers: {
507
- Authorization: `Bearer ${token}`,
508
- },
509
- });
510
-
511
- const text = await res.text().catch(() => "");
512
- let json;
513
- try {
514
- json = text ? JSON.parse(text) : {};
515
- } catch {
516
- json = {};
517
- }
518
-
519
- if (!res.ok) {
520
- const msg = (json && json.error) || text || `HTTP ${res.status}`;
521
- throw new Error(msg);
522
- }
523
-
524
- if (!json.ok) {
525
- throw new Error(json.error || "Failed to fetch user info");
526
- }
527
-
528
- return json; // { ok, username, is_admin }
529
- }
530
-
531
-
532
- export async function registerUser(username, password, token, overwrite = false) {
533
- const res = await fetch(`${API_BASE}/register`, {
534
- method: "POST",
535
- headers: {
536
- "Content-Type": "application/json",
537
- Authorization: `Bearer ${token}`,
538
- },
539
- body: JSON.stringify({ username, password, overwrite }),
540
- });
541
-
542
- const text = await res.text().catch(() => "");
543
- let json;
544
- try {
545
- json = text ? JSON.parse(text) : {};
546
- } catch {
547
- json = {};
548
- }
549
-
550
- if (!res.ok) {
551
- const msg = (json && json.error) || text || `HTTP ${res.status}`;
552
- throw new Error(msg);
553
- }
554
-
555
- if (!json.ok) {
556
- throw new Error(json.error || "Register failed");
557
- }
558
-
559
- return json; // { ok, username }
560
- }
561
-
 
10
 
11
  let json;
12
  const text = await res.text().catch(() => "");
 
13
  try {
14
  json = text ? JSON.parse(text) : {};
15
  } catch {
16
  json = {};
17
  }
18
 
 
19
  if (!res.ok) {
20
+ throw new Error(json?.error || text || `Login failed (${res.status})`);
 
 
 
 
21
  }
 
 
22
  if (!json.ok || !json.token) {
23
+ throw new Error(json?.error || "Login failed");
24
  }
 
25
  return json; // { ok, token }
26
  }
27
 
28
+ export async function streamChat(
29
+ message,
30
+ history,
31
+ token,
32
+ onToken,
33
+ sessionId = null,
34
+ onStatus = null,
35
+ onDebug = null
36
+ ) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  const res = await fetch(`${API_BASE}/chat/stream`, {
38
  method: "POST",
39
  headers: {
40
  "Content-Type": "application/json",
41
+ Authorization: `Bearer ${token}`,
42
  },
43
+ body: JSON.stringify({ message, history, session_id: sessionId }),
 
 
 
 
 
44
  });
45
 
46
+ if (!res.body) throw new Error("Streaming not supported");
 
 
47
 
48
  const reader = res.body.getReader();
49
  const decoder = new TextDecoder();
 
53
  const { value, done } = await reader.read();
54
  if (done) break;
55
 
56
+ buffer += decoder.decode(value);
 
57
 
58
+ // Parse status messages: __STATUS__:{"message":"..."}__END__
59
+ const statusRe = /__STATUS__:(.*?)__END__/g;
60
+ const debugRe = /__DEBUG__:(.*?)__END__/g;
 
61
  let match;
62
  let lastIndex = 0;
63
 
64
+ while ((match = statusRe.exec(buffer)) !== null) {
 
65
  if (match.index > lastIndex) {
66
  const content = buffer.substring(lastIndex, match.index);
67
  if (content) onToken(content);
68
  }
 
 
69
  try {
70
+ const data = JSON.parse(match[1]);
71
+ if (onStatus && data.message) onStatus(data.message);
72
+ } catch {}
73
+ lastIndex = statusRe.lastIndex;
 
 
 
 
 
74
  }
75
+
76
+ // Parse debug markers
77
+ debugRe.lastIndex = 0;
78
+ while ((match = debugRe.exec(buffer)) !== null) {
79
  try {
80
+ const data = JSON.parse(match[1]);
81
+ if (onDebug) onDebug(data);
82
+ buffer = buffer.substring(0, match.index) + buffer.substring(debugRe.lastIndex);
83
+ debugRe.lastIndex = match.index;
84
+ } catch {}
 
 
 
 
 
 
 
85
  }
86
 
87
+ // Emit remaining content
88
  if (lastIndex < buffer.length) {
89
  const content = buffer.substring(lastIndex);
 
90
  if (!content.includes("__STATUS__") && !content.includes("__DEBUG__")) {
91
  onToken(content);
92
  buffer = "";
93
  } else {
94
+ const markerStart = Math.max(
 
95
  content.lastIndexOf("__STATUS__"),
96
  content.lastIndexOf("__DEBUG__")
97
  );
98
+ if (markerStart > 0) {
99
+ onToken(content.substring(0, markerStart));
100
+ buffer = content.substring(markerStart);
101
  } else {
102
  buffer = content;
103
  }
 
105
  }
106
  }
107
 
108
+ // Flush remaining
109
  if (buffer && !buffer.includes("__STATUS__") && !buffer.includes("__DEBUG__")) {
110
  onToken(buffer);
111
  }
112
  }