File size: 12,901 Bytes
136f9cf
5fc68b0
 
 
 
 
12621bc
 
 
136f9cf
 
12621bc
 
 
136f9cf
 
 
 
5fc68b0
 
 
 
136f9cf
5fc68b0
136f9cf
5fc68b0
136f9cf
5fc68b0
 
 
 
 
 
 
 
 
 
 
136f9cf
5fc68b0
 
 
 
 
136f9cf
 
 
 
 
 
 
 
 
5fc68b0
 
 
 
136f9cf
 
 
 
 
5fc68b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136f9cf
5fc68b0
 
 
136f9cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fc68b0
12621bc
5fc68b0
 
12621bc
5fc68b0
 
136f9cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12621bc
136f9cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fc68b0
136f9cf
5fc68b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136f9cf
 
12621bc
136f9cf
 
 
 
 
 
 
 
 
 
 
 
12621bc
136f9cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fc68b0
 
 
 
136f9cf
 
5fc68b0
136f9cf
 
 
 
 
 
 
 
 
 
 
 
5fc68b0
136f9cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fc68b0
9249538
 
 
136f9cf
9249538
5fc68b0
 
136f9cf
 
 
 
 
 
 
5fc68b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9249538
5fc68b0
 
 
 
 
 
 
 
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
import React, { useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { useLiveQuery } from "dexie-react-hooks";
import { mapStoredMessageToChatMessage } from "@langchain/core/messages";
import { ConfigManager } from "@/lib/config/manager";
import { toast } from "sonner";
import { Messages } from "./components/Messages";
import { Input } from "./components/Input";
import { FilePreviewDialog } from "./components/FilePreviewDialog";
import { useChatSession, useSelectedModel, generateMessage, useChatManager } from "@/hooks/use-chat";
import { CHAT_MODELS, PROVIDERS } from "@/lib/config/types";
import { IDocument } from "@/lib/document/types";
import { HumanMessage } from "@langchain/core/messages";
import { AIMessageChunk } from "@langchain/core/messages";
import { DocumentManager } from "@/lib/document/manager";
import { useLoading } from "@/contexts/loading-context";
import { Alert, AlertTitle, AlertDescription } from "@/components/ui/alert";
import { AlertCircle } from "lucide-react";

export function ChatPage() {
  const { id } = useParams();
  const navigate = useNavigate();
  const { startLoading, stopLoading } = useLoading();

  // Use singleton instances
  const configManager = React.useMemo(() => ConfigManager.getInstance(), []);
  const chatManager = useChatManager();
  const documentManager = React.useMemo(() => DocumentManager.getInstance(), []);

  const [input, setInput] = React.useState("");
  const [attachments, setAttachments] = React.useState<IDocument[]>([]);
  const [isUrlInputOpen, setIsUrlInputOpen] = React.useState(false);
  const [urlInput, setUrlInput] = React.useState("");
  const [previewDocument, setPreviewDocument] = React.useState<IDocument | null>(null);
  const [isGenerating, setIsGenerating] = React.useState(false);
  const [streamingHumanMessage, setStreamingHumanMessage] = React.useState<HumanMessage | null>(null);
  const [streamingAIMessageChunks, setStreamingAIMessageChunks] = React.useState<AIMessageChunk[]>([]);
  const [editingMessageIndex, setEditingMessageIndex] = React.useState<number | null>(null);
  const [error, setError] = React.useState<string | null>(null);

  const config = useLiveQuery(async () => await configManager.getConfig());
  const chatSession = useChatSession(id);
  const [selectedModel, setSelectedModel, chatHistoryDB] = useSelectedModel(id, config);

  // Show loading screen during initial config load
  useEffect(() => {
    if (!config) {
      startLoading("Loading configuration...");
      return;
    }
    stopLoading();
  }, [config, startLoading, stopLoading]);

  const selectedModelName = React.useMemo(() => (
    CHAT_MODELS.find(model => model.model === selectedModel)?.name || "Select a model"
  ), [selectedModel]);

  const selectedModelProvider = React.useMemo(() => {
    const model = CHAT_MODELS.find(model => model.model === selectedModel);
    return model?.provider;
  }, [selectedModel]);

  const handleModelChange = React.useCallback(async (model: string) => {
    if (!config) return;
    
    if (!id || id === "new") {
      await configManager.updateConfig({
        ...config,
        default_chat_model: model
      });
    } else {
      const session = await chatHistoryDB.sessions.get(id);
      if (session) {
        await chatHistoryDB.sessions.update(id, {
          ...session,
          model,
          updatedAt: Date.now()
        });
      }
    }
    setSelectedModel(model);
    setError(null); // Clear any previous errors when changing models
  }, [config, id, setSelectedModel, configManager, chatHistoryDB.sessions]);

  const handleSendMessage = React.useCallback(async () => {
    // Clear any previous errors
    setError(null);
    
    // Check if trying to use Ollama when it's not available or not configured
    if (selectedModelProvider === PROVIDERS.ollama && config) {
      if (!config.ollama_base_url || config.ollama_base_url.trim() === '') {
        setError(`Ollama base URL is not configured. Please set a valid URL in the settings.`);
        return;
      }
      
      if (!config.ollama_available) {
        setError(`Ollama server is not available. Please check your connection to ${config.ollama_base_url}`);
        return;
      }
    }
    
    let chatId = id;
    let isNewChat = false;
    if (id === "new") {
      chatId = crypto.randomUUID();
      isNewChat = true;
      navigate(`/chat/${chatId}`, { replace: true });
    }
    
    // Reset controller before starting a new chat
    chatManager.resetController();
    
    try {
      await generateMessage(
        chatId, 
        input, 
        attachments, 
        isGenerating, 
        setIsGenerating, 
        setStreamingHumanMessage, 
        setStreamingAIMessageChunks, 
        chatManager, 
        setInput, 
        setAttachments
      );

      if (isNewChat && chatId) {
        const chatName = await chatManager.chatChain(
          `Based on this user message, generate a very concise (max 40 chars) but descriptive name for this chat: "${input}"`,
          "You are a helpful assistant that generates concise chat names. Respond only with the name, no quotes or explanation."
        );
        await chatHistoryDB.sessions.update(chatId, {
          name: String(chatName.content)
        });
      }
    } catch (error) {
      console.error("Error sending message:", error);
      if (error instanceof Error) {
        setError(error.message);
      } else {
        setError("An unknown error occurred while sending your message");
      }
    }
  }, [id, input, attachments, isGenerating, chatManager, navigate, chatHistoryDB.sessions, selectedModelProvider, config]);
  
  const handleAttachmentFileUpload = React.useCallback(async (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    if (!files) return;

    try {
      const newDocs = await Promise.all(
        Array.from(files).map(file => documentManager.uploadDocument(file))
      );
      setAttachments(prev => [...prev, ...newDocs]);
    } catch (error) {
      console.error(error);
      toast.error("Failed to upload files");
    }
  }, [documentManager]);
  
  const handleAttachmentUrlUpload = React.useCallback(async () => {
    if (!urlInput.trim()) return;

    try {
      const urls = urlInput.split(",").map(url => url.trim());
      const newDocs = await Promise.all(
        urls.map(url => documentManager.uploadUrl(url))
      );
      setAttachments(prev => [...prev, ...newDocs]);
      setUrlInput("");
      setIsUrlInputOpen(false);
    } catch (error) {
      console.error(error);
      toast.error("Failed to upload URLs");
    }
  }, [urlInput, documentManager]);

  const handleAttachmentRemove = React.useCallback((docId: string) => {
    setAttachments(prev => prev.filter(doc => doc.id !== docId));
  }, []);

  const handleEditMessage = React.useCallback((index: number) => {
    setEditingMessageIndex(index);
  }, []);

  const handleSaveEdit = React.useCallback(async (content: string) => {
    if (!id || editingMessageIndex === null || !chatSession || isGenerating) return;

    // Clear any previous errors
    setError(null);
    
    // Check if trying to use Ollama when it's not available or not configured
    if (selectedModelProvider === PROVIDERS.ollama && config) {
      if (!config.ollama_base_url || config.ollama_base_url.trim() === '') {
        setError(`Ollama base URL is not configured. Please set a valid URL in the settings.`);
        return;
      }
      
      if (!config.ollama_available) {
        setError(`Ollama server is not available. Please check your connection to ${config.ollama_base_url}`);
        return;
      }
    }

    try {
      // Update the message directly in the database
      const updatedMessages = [...chatSession.messages];
      updatedMessages[editingMessageIndex] = {
        ...updatedMessages[editingMessageIndex],
        data: {
          ...updatedMessages[editingMessageIndex].data,
          content
        }
      };
      // Remove messages after the edited message
      const newMessages = updatedMessages.slice(0, editingMessageIndex + 1);
      
      await chatHistoryDB.sessions.update(id, {
        ...chatSession,
        messages: newMessages,
        updatedAt: Date.now()
      });
      
      setInput(content);
      setEditingMessageIndex(null);
      setAttachments([]);

      // Reset controller before regenerating
      chatManager.resetController();
      
      await generateMessage(
        id, 
        content, 
        [], 
        isGenerating, 
        setIsGenerating, 
        setStreamingHumanMessage, 
        setStreamingAIMessageChunks, 
        chatManager, 
        setInput, 
        setAttachments
      );
    } catch (error) {
      console.error("Error editing message:", error);
      if (error instanceof Error) {
        setError(error.message);
      } else {
        setError("An unknown error occurred while editing your message");
      }
    }
  }, [id, editingMessageIndex, chatSession, isGenerating, chatHistoryDB.sessions, chatManager, selectedModelProvider, config]);

  const handleRegenerateMessage = React.useCallback(async (index: number) => {
    if (!id || !chatSession || isGenerating) return;

    // Clear any previous errors
    setError(null);
    
    // Check if trying to use Ollama when it's not available or not configured
    if (selectedModelProvider === PROVIDERS.ollama && config) {
      if (!config.ollama_base_url || config.ollama_base_url.trim() === '') {
        setError(`Ollama base URL is not configured. Please set a valid URL in the settings.`);
        return;
      }
      
      if (!config.ollama_available) {
        setError(`Ollama server is not available. Please check your connection to ${config.ollama_base_url}`);
        return;
      }
    }

    try {
      const messages = chatSession.messages;
      if (messages.length <= index) return;
      
      const message = messages[index];
      const content = message.data.content;

      // Remove messages after the current message
      const newMessages = messages.slice(0, index + 1);
      
      await chatHistoryDB.sessions.update(id, {
        ...chatSession,
        messages: newMessages,
        updatedAt: Date.now()
      });
      
      // Reset controller before regenerating
      chatManager.resetController();
      
      await generateMessage(
        id, 
        content, 
        [], 
        isGenerating, 
        setIsGenerating, 
        setStreamingHumanMessage, 
        setStreamingAIMessageChunks, 
        chatManager, 
        setInput, 
        setAttachments
      );
    } catch (error) {
      console.error("Error regenerating message:", error);
      if (error instanceof Error) {
        setError(error.message);
      } else {
        setError("An unknown error occurred while regenerating the message");
      }
    }
  }, [id, chatSession, isGenerating, chatHistoryDB.sessions, chatManager, selectedModelProvider, config]);

  const stopGenerating = React.useCallback(() => {
    chatManager.controller.abort();
    setIsGenerating(false);
  }, [chatManager]);

  return (
    <div className="flex flex-col h-screen p-2">
      {error && (
        <Alert variant="destructive" className="mb-4">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>Error</AlertTitle>
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}
      <Messages
        messages={chatSession?.messages.map(mapStoredMessageToChatMessage)}
        streamingHumanMessage={streamingHumanMessage}
        streamingAIMessageChunks={streamingAIMessageChunks}
        setPreviewDocument={setPreviewDocument}
        onEditMessage={handleEditMessage}
        onRegenerateMessage={handleRegenerateMessage}
        editingMessageIndex={editingMessageIndex}
        onSaveEdit={handleSaveEdit}
        onCancelEdit={() => setEditingMessageIndex(null)}
      />
      <Input
        input={input}
        selectedModel={selectedModel || ""}
        attachments={attachments}
        onInputChange={setInput}
        onModelChange={handleModelChange}
        onSendMessage={handleSendMessage}
        enabledChatModels={config?.enabled_chat_models}
        setPreviewDocument={setPreviewDocument}
        isUrlInputOpen={isUrlInputOpen}
        setIsUrlInputOpen={setIsUrlInputOpen}
        urlInput={urlInput}
        setUrlInput={setUrlInput}
        handleAttachmentFileUpload={handleAttachmentFileUpload}
        handleAttachmentUrlUpload={handleAttachmentUrlUpload}
        handleAttachmentRemove={handleAttachmentRemove}
        selectedModelName={selectedModelName}
        isGenerating={isGenerating}
        stopGenerating={stopGenerating}
      />
      <FilePreviewDialog
        document={previewDocument}
        onClose={() => setPreviewDocument(null)}
      />
    </div>
  );
}