File size: 12,304 Bytes
c49440d
 
 
 
 
 
 
 
 
 
ee2c134
c49440d
 
ee2c134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c49440d
 
 
 
 
 
 
 
 
 
 
 
ee2c134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89096eb
 
 
ee2c134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89096eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c49440d
 
 
 
 
 
 
 
 
89096eb
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee2c134
 
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89096eb
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee2c134
 
 
 
 
 
 
 
 
 
 
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89096eb
 
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
89096eb
c49440d
 
 
 
 
 
89096eb
 
 
 
 
 
 
 
 
 
 
 
 
 
c49440d
 
89096eb
 
 
 
 
 
 
 
c49440d
 
ee2c134
c49440d
 
 
 
 
 
 
 
 
 
 
ee2c134
c49440d
 
 
ee2c134
c49440d
ee2c134
 
 
 
 
 
 
 
89096eb
c49440d
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import React, { useState, useEffect } from "react";
import { AnimatedAIChat } from "@/components/ui/animated-ai-chat";

export function App() {
  const [models, setModels] = useState<Record<string, string>>({});
  const [chapters, setChapters] = useState<string[]>([]);
  const [selectedModel, setSelectedModel] = useState<string>("@cf/deepseek-ai/deepseek-r1-distill-qwen-32b");
  const [selectedChapter, setSelectedChapter] = useState<string>("All");
  const [messages, setMessages] = useState<any[]>([]);
  const [isStreaming, setIsStreaming] = useState(false);
  const [isSessionLoading, setIsSessionLoading] = useState(false);
  const [groqKeysCount, setGroqKeysCount] = useState<number>(0);

  // User auth state (stored in localStorage)
  const [user, setUser] = useState<{ username: string; name: string } | null>(() => {
    try {
      const saved = localStorage.getItem("jurisai_user");
      return saved ? JSON.parse(saved) : null;
    } catch {
      return null;
    }
  });

  // Sessions list and current session id
  const [sessions, setSessions] = useState<Array<{ id: string; title: string; updated_at: string }>>([]);
  const [currentSessionId, setCurrentSessionId] = useState<string | null>(null);

  // Fetch initial info (models, chapters, groq keys)
  useEffect(() => {
    fetch("/api/info")
      .then((res) => res.json())
      .then((data) => {
        setModels(data.models || {});
        setChapters(data.chapters || []);
        if (data.default_model) setSelectedModel(data.default_model);
        if (typeof data.groq_keys_count === "number") setGroqKeysCount(data.groq_keys_count);
      })
      .catch((e) => console.error("Error fetching info:", e));
  }, []);

  // Fetch user's session list
  const loadSessions = async (username?: string) => {
    try {
      const u = username || user?.username;
      const url = u ? `/api/sessions?username=${encodeURIComponent(u)}` : "/api/sessions";
      const res = await fetch(url);
      const data = await res.json();
      setSessions(data.sessions || []);
    } catch (e) {
      console.error("Error fetching sessions:", e);
    }
  };

  useEffect(() => {
    loadSessions();
  }, [user]);

  // Handle URL share / session query parameters
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const sid = params.get("session") || params.get("share");
    if (sid) {
      loadSessionById(sid);
    }
  }, []);

  const loadSessionById = async (sid: string) => {
    // Immediately select session and show loading skeleton
    setCurrentSessionId(sid);
    setMessages([]);
    setIsSessionLoading(true);
    try {
      const res = await fetch(`/api/sessions/${sid}`);
      if (!res.ok) return;
      const data = await res.json();
      if (data.model) setSelectedModel(data.model);
      if (data.chapter_filter) setSelectedChapter(data.chapter_filter);

      if (data.messages && Array.isArray(data.messages)) {
        setMessages(
          data.messages.map((m: any) => ({
            role: m.role,
            content: m.content || "",
            thinking: m.thinking || "",
            findings: m.findings || null,
            citations: m.citations || [],
            usage: m.usage || { completion_tokens: 0 },
          }))
        );
      }
      // Update browser URL without reloading
      const url = new URL(window.location.href);
      url.searchParams.set("session", data.id);
      window.history.replaceState({}, "", url.toString());
    } catch (e) {
      console.error("Error loading session:", e);
    } finally {
      setIsSessionLoading(false);
    }
  };

  const handleDeleteSession = async (sid: string) => {
    try {
      await fetch(`/api/sessions/${sid}`, { method: "DELETE" });
      // If deleting current session, clear thread
      if (sid === currentSessionId) {
        handleClear();
      }
      // Refresh list
      loadSessions();
    } catch (e) {
      console.error("Error deleting session:", e);
    }
  };

  const handleAuth = async (
    username: string,
    name?: string,
    mode: "create" | "login" = "create"
  ): Promise<{ success: boolean; error?: string }> => {
    try {
      const res = await fetch("/api/auth", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, name, mode }),
      });
      const data = await res.json();
      if (!res.ok) {
        return { success: false, error: data.detail || "Authentication failed." };
      }
      setUser(data);
      localStorage.setItem("jurisai_user", JSON.stringify(data));
      loadSessions(data.username);
      return { success: true };
    } catch (e: any) {
      console.error("Auth error:", e);
      return { success: false, error: e.message || "Failed to connect to authentication server." };
    }
  };

  const handleLogout = () => {
    setUser(null);
    localStorage.removeItem("jurisai_user");
    loadSessions("");
  };

  const handleClear = () => {
    setMessages([]);
    setCurrentSessionId(null);
    const url = new URL(window.location.href);
    url.searchParams.delete("session");
    url.searchParams.delete("share");
    window.history.replaceState({}, "", url.toString());
  };

  const handleShareSession = () => {
    if (!currentSessionId) return;
    const shareUrl = `${window.location.origin}${window.location.pathname}?session=${encodeURIComponent(currentSessionId)}`;
    navigator.clipboard.writeText(shareUrl);
  };

  const handleCompactSession = async () => {
    if (!currentSessionId) return;
    try {
      const res = await fetch(`/api/sessions/${currentSessionId}/compact`, {
        method: "POST"
      });
      if (res.ok) {
        const data = await res.json();
        if (data.session && Array.isArray(data.session.messages)) {
          setMessages(
            data.session.messages.map((m: any) => ({
              role: m.role,
              content: m.content || "",
              thinking: m.thinking || "",
              findings: m.findings || null,
              citations: m.citations || [],
              usage: m.usage || { completion_tokens: 0 },
            }))
          );
        }
        loadSessions();
      }
    } catch (e) {
      console.error("Compaction failed:", e);
    }
  };

  const handleSendMessage = async (userText: string) => {
    const userMsg = { role: "user", content: userText };
    const initialAssistantMsg = {
      role: "assistant",
      content: "",
      thinking: "",
      findings: null,
      citations: [],
      usage: { completion_tokens: 0 },
      isInterrupted: false,
    };

    const newHistory = [...messages, userMsg];
    setMessages([...newHistory, initialAssistantMsg]);
    setIsStreaming(true);

    try {
      const historyPayload = messages.map((m) => ({
        role: m.role,
        content: m.content || "",
      }));

      const res = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          query: userText,
          history: historyPayload,
          model: selectedModel,
          chapter_filter: selectedChapter,
          top_k: 5,
          session_id: currentSessionId || undefined,
          username: user?.username || undefined,
        }),
      });

      if (!res.body) {
        setIsStreaming(false);
        return;
      }

      const reader = res.body.getReader();
      const decoder = new TextDecoder();
      let buffer = "";

      let answerText = "";
      let thinkingText = "";
      let findingsData: any = null;
      let citationsData: any[] = [];
      let tokenUsage: any = { completion_tokens: 0 };
      let hasReceivedDone = false;

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });
        const events = buffer.split("\n\n");
        buffer = events.pop() || "";

        for (const evt of events) {
          if (!evt.trim()) continue;
          const lines = evt.split("\n");
          let eventType = "message";
          let dataStr = "";

          for (const line of lines) {
            if (line.startsWith("event: ")) {
              eventType = line.slice(7).trim();
            } else if (line.startsWith("data: ")) {
              dataStr = line.slice(6).trim();
            }
          }

          if (eventType === "session" && dataStr) {
            try {
              const obj = JSON.parse(dataStr);
              if (obj.session_id) {
                setCurrentSessionId(obj.session_id);
                const url = new URL(window.location.href);
                url.searchParams.set("session", obj.session_id);
                window.history.replaceState({}, "", url.toString());
              }
            } catch (e) {}
          } else if (eventType === "findings" && dataStr) {
            try {
              findingsData = JSON.parse(dataStr);
            } catch (e) {}
          } else if (eventType === "thinking" && dataStr) {
            try {
              const obj = JSON.parse(dataStr);
              thinkingText += obj.text || "";
            } catch (e) {}
          } else if (eventType === "token" && dataStr) {
            try {
              const obj = JSON.parse(dataStr);
              answerText += obj.text || "";
            } catch (e) {}
          } else if (eventType === "citations" && dataStr) {
            try {
              citationsData = JSON.parse(dataStr);
            } catch (e) {}
          } else if (eventType === "usage" && dataStr) {
            try {
              const obj = JSON.parse(dataStr);
              tokenUsage = { ...tokenUsage, ...obj };
            } catch (e) {}
          } else if (eventType === "done") {
            hasReceivedDone = true;
          }

          setMessages((prev) => {
            const updated = [...prev];
            const lastIdx = updated.length - 1;
            if (lastIdx >= 0 && updated[lastIdx].role === "assistant") {
              updated[lastIdx] = {
                ...updated[lastIdx],
                content: answerText,
                thinking: thinkingText,
                findings: findingsData,
                citations: citationsData,
                usage: tokenUsage,
                isInterrupted: false,
              };
            }
            return updated;
          });
        }
      }

      // Check if response ended abruptly or failed to complete
      const isLikelyAbrupt = !hasReceivedDone && answerText.length > 0 && !answerText.trim().endsWith(".") && !answerText.trim().endsWith("!") && !answerText.trim().endsWith("?") && !answerText.trim().endsWith("`") && !answerText.trim().endsWith("*") && !answerText.trim().endsWith(")");
      if (isLikelyAbrupt) {
        setMessages((prev) => {
          const updated = [...prev];
          const lastIdx = updated.length - 1;
          if (lastIdx >= 0 && updated[lastIdx].role === "assistant") {
            updated[lastIdx].isInterrupted = true;
          }
          return updated;
        });
      }

    } catch (e) {
      console.error("Stream error:", e);
      setMessages((prev) => {
        const updated = [...prev];
        const lastIdx = updated.length - 1;
        if (lastIdx >= 0 && updated[lastIdx].role === "assistant") {
          updated[lastIdx].isInterrupted = true;
        }
        return updated;
      });
    } finally {
      setIsStreaming(false);
      loadSessions();
    }
  };

  return (
    <AnimatedAIChat
      models={models}
      chapters={chapters}
      selectedModel={selectedModel}
      onSelectModel={setSelectedModel}
      selectedChapter={selectedChapter}
      onSelectChapter={setSelectedChapter}
      onClear={handleClear}
      messages={messages}
      onSendMessage={handleSendMessage}
      isStreaming={isStreaming}
      isSessionLoading={isSessionLoading}
      groqKeysCount={groqKeysCount}
      user={user}
      onAuth={handleAuth}
      onLogout={handleLogout}
      sessions={sessions}
      currentSessionId={currentSessionId}
      onSelectSession={loadSessionById}
      onShareSession={handleShareSession}
      onDeleteSession={handleDeleteSession}
      onCompactSession={handleCompactSession}
    />
  );
}

export default App;