@@ -1,234 +1,41 @@
11 "use client";
2-import { useState, useEffect, useRef } from "react";
3-import ReactMarkdown from "react-markdown";
4-import remarkGfm from "remark-gfm";
5-import rehypeHighlight from "rehype-highlight";
2+import { useRef } from "react";
63 import Sidebar from "@/src/components/Sidebar";
74 import MessageInput, { type MessageInputRef } from "@/src/components/MessageInput";
5+import MessageList from "@/src/components/MessageList";
86 import NoThreadSelected from "@/src/components/NoThreadSelected";
97 import { useTheme } from "@/src/hooks/useTheme";
10-import type { Thread, Message } from "@/src/lib/db/schema";
8+import { useThreads } from "@/src/hooks/useThreads";
9+import { useMessages } from "@/src/hooks/useMessages";
10+import { useThreadSelection } from "@/src/hooks/useThreadSelection";
1111 import "./highlight-theme.css";
1212
1313 export default function Home() {
14- const [messages, setMessages] = useState<Message[]>([]);
1514 const { themeMode, handleThemeChange } = useTheme();
16- const [currentThreadId, setCurrentThreadId] = useState<number | null>(null);
17- const [threads, setThreads] = useState<Thread[]>([]);
18- const [totalThreadCount, setTotalThreadCount] = useState<number>(0);
19- const [isLoading, setIsLoading] = useState(false);
20- const [hasMoreThreads, setHasMoreThreads] = useState(true);
21- const messagesContainerRef = useRef<HTMLDivElement>(null);
22- const messageRefs = useRef<Map<number, HTMLDivElement>>(new Map());
23- const prevMessagesLengthRef = useRef<number>(0);
15+ const { threads, totalThreadCount, hasMoreThreads, loadThreads, loadMoreThreads, createThread } =
16+ useThreads();
17+ const { currentThreadId, selectThread, deselectThread, messagesContainerRef } =
18+ useThreadSelection();
19+ const { messages, isLoading, sendMessage, clearMessages } = useMessages(currentThreadId);
2420 const messageInputRef = useRef<MessageInputRef>(null);
2521
26- useEffect(() => {
27- const loadThreads = async () => {
28- try {
29- const res = await fetch("/api/threads?limit=8");
30- const data = await res.json();
31- const threadsList = data.threads || [];
32- setThreads(threadsList);
33- setHasMoreThreads(data.hasMore || false);
34- setTotalThreadCount(data.totalCount || 0);
35- } catch (error) {
36- console.error("Failed to load threads", error);
37- }
38- };
39-
40- loadThreads();
41- }, []);
42-
43- useEffect(() => {
44- // Scroll to top when a thread is selected
45- if (currentThreadId !== null && messagesContainerRef.current) {
46- messagesContainerRef.current.scrollTop = 0;
47- }
48- }, [currentThreadId]);
49-
50- useEffect(() => {
51- // Scroll to the start of the newly added message
52- if (messages.length > prevMessagesLengthRef.current) {
53- const newMessage = messages[messages.length - 1];
54- const messageElement = messageRefs.current.get(newMessage.id);
55- if (messageElement) {
56- messageElement.scrollIntoView({ block: "start", behavior: "instant" });
57- }
58- prevMessagesLengthRef.current = messages.length;
59- }
60- }, [messages]);
61-
62- const loadMessages = async (threadId: number) => {
63- try {
64- const res = await fetch(`/api/threads/${threadId}/messages`);
65- const data = await res.json();
66- const loadedMessages = data.messages || [];
67- setMessages(loadedMessages);
68- prevMessagesLengthRef.current = loadedMessages.length;
69- } catch (error) {
70- console.error("Failed to load messages", error);
71- }
72- };
73-
74- const createNewThread = async (
75- titleOverride?: string,
76- firstMessage?: string
77- ): Promise<number | null> => {
78- try {
79- const title = titleOverride || (firstMessage ? firstMessage.substring(0, 100) : "New Thread");
80- const res = await fetch("/api/threads", {
81- method: "POST",
82- headers: { "Content-Type": "application/json" },
83- body: JSON.stringify({ title }),
84- });
85- const data = await res.json();
86- const newThread = data.thread;
87- setCurrentThreadId(newThread.id);
88- setMessages([]);
89- prevMessagesLengthRef.current = 0;
90- // Reload threads to get the full list
91- const threadsRes = await fetch("/api/threads?limit=8");
92- const threadsData = await threadsRes.json();
93- const threadsList = threadsData.threads || [];
94- setThreads(threadsList);
95- setHasMoreThreads(threadsData.hasMore || false);
96- setTotalThreadCount(threadsData.totalCount || 0);
97- return newThread.id;
98- } catch (error) {
99- console.error("Failed to create thread", error);
100- return null;
101- }
102- };
103-
10422 const handleThreadSelect = (threadId: number) => {
105- setCurrentThreadId(threadId);
106- loadMessages(threadId);
23+ selectThread(threadId);
10724 };
10825
10926 const handleCreateNewThread = () => {
110- setCurrentThreadId(null);
111- setMessages([]);
112- prevMessagesLengthRef.current = 0;
27+ deselectThread();
28+ clearMessages();
11329 // Focus the input after a short delay to ensure DOM has updated
11430 setTimeout(() => {
11531 messageInputRef.current?.focus();
11632 }, 0);
11733 };
11834
119- const loadMoreThreads = async () => {
120- try {
121- const offset = threads.length;
122- const res = await fetch(`/api/threads?offset=${offset}&limit=8`);
123- const data = await res.json();
124- const newThreads = data.threads || [];
125- if (newThreads.length > 0) {
126- setThreads((prev) => [...prev, ...newThreads]);
127- setHasMoreThreads(data.hasMore || false);
128- } else {
129- setHasMoreThreads(false);
130- }
131- } catch (error) {
132- console.error("Failed to load more threads", error);
133- }
35+ const handleSendMessage = async (message: string) => {
36+ await sendMessage(message, currentThreadId, createThread, selectThread, loadThreads);
13437 };
13538
136- const sendMessage = async (message: string) => {
137- if (!message.trim() || isLoading) return;
138-
139- setIsLoading(true);
140- let threadId = currentThreadId;
141- if (!threadId) {
142- // Create a new thread if none exists
143- threadId = await createNewThread(message.substring(0, 100), message);
144- if (!threadId) {
145- setIsLoading(false);
146- return;
147- }
148- }
149-
150- const userMsg: Message = {
151- id: Date.now(),
152- threadId: threadId!,
153- role: "user",
154- content: message,
155- createdAt: new Date(),
156- generationTimeMs: null,
157- toolCalls: null,
158- };
159- setMessages((prev) => [...prev, userMsg]);
160-
161- try {
162- const res = await fetch("/api/chat", {
163- method: "POST",
164- headers: { "Content-Type": "application/json" },
165- body: JSON.stringify({ message: message.trim(), threadId }),
166- });
167-
168- const data = await res.json();
169-
170- const botMsg: Message = {
171- id: Date.now() + 1,
172- threadId: threadId!,
173- role: "assistant",
174- content: data.answer || "",
175- createdAt: new Date(),
176- generationTimeMs: null,
177- toolCalls: null,
178- };
179- setMessages((prev) => [...prev, botMsg]);
180-
181- // Reload messages to get correct IDs from database
182- await loadMessages(threadId!);
183-
184- // Reload threads to update the order
185- const threadsRes = await fetch("/api/threads?limit=8");
186- const threadsData = await threadsRes.json();
187- const threadsList = threadsData.threads || [];
188- setThreads(threadsList);
189- setHasMoreThreads(threadsData.hasMore || false);
190- setTotalThreadCount(threadsData.totalCount || 0);
191- } catch (error) {
192- console.error("Failed to send message", error);
193- } finally {
194- setIsLoading(false);
195- }
196- };
197-
198- const formatTimestamp = (date: Date | string): string => {
199- const d = typeof date === "string" ? new Date(date) : date;
200- return d.toLocaleString();
201- };
202-
203- const formatGenerationTime = (ms: number | null): string => {
204- if (!ms) return "";
205- if (ms < 1000) return `${ms}ms`;
206- return `${(ms / 1000).toFixed(1)}s`;
207- };
208-
209- const formatToolCalls = (toolCallsJson: string | null): string | null => {
210- if (!toolCallsJson) return null;
211- try {
212- const toolCalls = JSON.parse(toolCallsJson);
213- if (!Array.isArray(toolCalls) || toolCalls.length === 0) return null;
214-
215- // Count occurrences of each tool name
216- const toolCounts: Record<string, number> = {};
217- toolCalls.forEach((tc: any) => {
218- const toolName = tc.function?.name || "unknown";
219- toolCounts[toolName] = (toolCounts[toolName] || 0) + 1;
220- });
221-
222- // Format as "toolName x count"
223- const formatted = Object.entries(toolCounts)
224- .map(([name, count]) => `${name} x ${count}`)
225- .join(", ");
226-
227- return formatted;
228- } catch {
229- return null;
230- }
231- };
23239
23340 return (
23441 <div className="flex h-screen bg-neutral-100 text-neutral-800 dark:bg-neutral-950 dark:text-neutral-200">
@@ -241,46 +48,7 @@ export default function Home() {
24148 {currentThreadId === null ? (
24249 <NoThreadSelected threadCount={totalThreadCount} />
24350 ) : (
244- messages.map((msg) => (
245- <div
246- key={msg.id}
247- ref={(el) => {
248- if (el) {
249- messageRefs.current.set(msg.id, el);
250- } else {
251- messageRefs.current.delete(msg.id);
252- }
253- }}
254- className="w-full min-w-0"
255- >
256- <div
257- className={`p-2 ${
258- msg.role === "assistant"
259- ? "prose prose-neutral max-w-none bg-neutral-200 dark:prose-invert dark:bg-neutral-900"
260- : "ml-auto w-1/2 min-w-64 bg-neutral-300 text-right dark:bg-neutral-800"
261- }`}
262- >
263- {msg.role === "assistant" ? (
264- <ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeHighlight]}>
265- {msg.content}
266- </ReactMarkdown>
267- ) : (
268- <div>{msg.content}</div>
269- )}
270- <div className="mt-1 text-xs text-neutral-600 dark:text-neutral-400">
271- sent on {formatTimestamp(msg.createdAt)}
272- {msg.role === "assistant" && msg.generationTimeMs && (
273- <span className="ml-1">
274- • generated in {formatGenerationTime(msg.generationTimeMs)}
275- </span>
276- )}
277- {msg.role === "assistant" && formatToolCalls(msg.toolCalls) && (
278- <span className="ml-1">• tools: {formatToolCalls(msg.toolCalls)}</span>
279- )}
280- </div>
281- </div>
282- </div>
283- ))
51+ <MessageList messages={messages} />
28452 )}
28553 </div>
28654 </div>
@@ -288,7 +56,7 @@ export default function Home() {
28856 ref={messageInputRef}
28957 isLoading={isLoading}
29058 messages={messages}
291- onSubmit={sendMessage}
59+ onSubmit={handleSendMessage}
29260 />
29361 </div>
29462 <Sidebar