xonecas.io
53129
Pa

PAT / commit f0dd25b

refactor: extract logic into smaller components and hooks

xonecas2025-12-17 f0dd25b93405c6d3b42c34c3006bcd33bcec9ee7 parent 008a500

11 files changed

app/page.tsx+17−249
@@ -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
src/components/MessageInput.tsx+3−6
@@ -2,6 +2,7 @@
22
33 import { useState, useRef, useImperativeHandle, forwardRef } from "react";
44 import PaperPlaneIcon from "@/src/components/icons/PaperPlaneIcon";
5+import PrimaryButton from "@/src/components/buttons/PrimaryButton";
56 import type { Message } from "@/src/lib/db/schema";
67
78 type MessageInputProps = {
@@ -78,13 +79,9 @@ const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
7879 disabled={isLoading}
7980 className="flex-1 bg-neutral-200 px-2 py-2 placeholder:italic placeholder:text-neutral-600 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 dark:bg-neutral-900 dark:placeholder:text-neutral-400"
8081 />
81- <button
82- type="submit"
83- disabled={isLoading}
84- className="bg-green-900 px-3 py-1 text-neutral-100 hover:bg-green-800 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-green-500 dark:text-neutral-900 dark:hover:bg-green-600"
85- >
82+ <PrimaryButton type="submit" disabled={isLoading}>
8683 <PaperPlaneIcon className={`h-5 w-5 ${isLoading ? "animate-spin" : ""}`} />
87- </button>
84+ </PrimaryButton>
8885 </form>
8986 );
9087 }
src/components/MessageList.tsx+110−0
@@ -0,0 +1,110 @@
1+"use client";
2+
3+import { useRef, useEffect } from "react";
4+import ReactMarkdown from "react-markdown";
5+import remarkGfm from "remark-gfm";
6+import rehypeHighlight from "rehype-highlight";
7+import type { Message } from "@/src/lib/db/schema";
8+import "../../app/highlight-theme.css";
9+
10+type MessageListProps = {
11+ messages: Message[];
12+};
13+
14+export default function MessageList({ messages }: MessageListProps) {
15+ const messageRefs = useRef<Map<number, HTMLDivElement>>(new Map());
16+ const prevMessagesLengthRef = useRef<number>(0);
17+
18+ useEffect(() => {
19+ // Scroll to the start of the newly added message
20+ if (messages.length > prevMessagesLengthRef.current) {
21+ const newMessage = messages[messages.length - 1];
22+ const messageElement = messageRefs.current.get(newMessage.id);
23+ if (messageElement) {
24+ messageElement.scrollIntoView({ block: "start", behavior: "instant" });
25+ }
26+ prevMessagesLengthRef.current = messages.length;
27+ }
28+ }, [messages]);
29+
30+ const formatTimestamp = (date: Date | string): string => {
31+ const d = typeof date === "string" ? new Date(date) : date;
32+ return d.toLocaleString();
33+ };
34+
35+ const formatGenerationTime = (ms: number | null): string => {
36+ if (!ms) return "";
37+ if (ms < 1000) return `${ms}ms`;
38+ return `${(ms / 1000).toFixed(1)}s`;
39+ };
40+
41+ const formatToolCalls = (toolCallsJson: string | null): string | null => {
42+ if (!toolCallsJson) return null;
43+ try {
44+ const toolCalls = JSON.parse(toolCallsJson);
45+ if (!Array.isArray(toolCalls) || toolCalls.length === 0) return null;
46+
47+ // Count occurrences of each tool name
48+ const toolCounts: Record<string, number> = {};
49+ toolCalls.forEach((tc: any) => {
50+ const toolName = tc.function?.name || "unknown";
51+ toolCounts[toolName] = (toolCounts[toolName] || 0) + 1;
52+ });
53+
54+ // Format as "toolName x count"
55+ const formatted = Object.entries(toolCounts)
56+ .map(([name, count]) => `${name} x ${count}`)
57+ .join(", ");
58+
59+ return formatted;
60+ } catch {
61+ return null;
62+ }
63+ };
64+
65+ return (
66+ <>
67+ {messages.map((msg) => (
68+ <div
69+ key={msg.id}
70+ ref={(el) => {
71+ if (el) {
72+ messageRefs.current.set(msg.id, el);
73+ } else {
74+ messageRefs.current.delete(msg.id);
75+ }
76+ }}
77+ className="w-full min-w-0"
78+ >
79+ <div
80+ className={`p-2 ${
81+ msg.role === "assistant"
82+ ? "prose prose-neutral max-w-none bg-neutral-200 dark:prose-invert dark:bg-neutral-900"
83+ : "ml-auto w-1/2 min-w-64 bg-neutral-300 text-right dark:bg-neutral-800"
84+ }`}
85+ >
86+ {msg.role === "assistant" ? (
87+ <ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeHighlight]}>
88+ {msg.content}
89+ </ReactMarkdown>
90+ ) : (
91+ <div>{msg.content}</div>
92+ )}
93+ <div className="mt-1 text-xs text-neutral-600 dark:text-neutral-400">
94+ sent on {formatTimestamp(msg.createdAt)}
95+ {msg.role === "assistant" && msg.generationTimeMs && (
96+ <span className="ml-1">
97+ • generated in {formatGenerationTime(msg.generationTimeMs)}
98+ </span>
99+ )}
100+ {msg.role === "assistant" && formatToolCalls(msg.toolCalls) && (
101+ <span className="ml-1">• tools: {formatToolCalls(msg.toolCalls)}</span>
102+ )}
103+ </div>
104+ </div>
105+ </div>
106+ ))}
107+ </>
108+ );
109+}
110+
src/components/NoThreadSelected.tsx+1−1
@@ -28,7 +28,7 @@ export default function NoThreadSelected({ threadCount }: NoThreadSelectedProps)
2828 return (
2929 <div className="mx-auto min-w-0 max-w-5xl">
3030 <div className="flex flex-col gap-4 bg-neutral-200 p-8 dark:bg-neutral-900">
31- <h1 className="text-4xl font-bold">Welcome to PAT 👋</h1>
31+ <h1 className="text-4xl font-bold">Hello, I'm PAT 👋</h1>
3232 <p>
3333 <strong>PAT</strong> (Personal Assistant Thing) is your personal assistant. Start typing
3434 below to start new a conversation thread or pick a previous conversation thread from the
src/components/Sidebar.tsx+9−17
@@ -3,6 +3,8 @@
33 import type { Thread } from "@/src/lib/db/schema";
44 import PlusIcon from "@/src/components/icons/PlusIcon";
55 import ChevronDownIcon from "@/src/components/icons/ChevronDownIcon";
6+import AlternateButton from "@/src/components/buttons/AlternateButton";
7+import SecondaryButton from "@/src/components/buttons/SecondaryButton";
68
79 type SidebarProps = {
810 threads: Thread[];
@@ -31,43 +33,33 @@ export default function Sidebar({
3133 <div className="flex flex-col gap-2">
3234 <label className="font-semibold">Threads</label>
3335 <div className="flex flex-col gap-1">
34- <button
35- onClick={() => onCreateNewThread()}
36- className="flex items-center justify-center gap-1 bg-indigo-200 px-1 py-1 text-indigo-900 hover:bg-indigo-300 dark:bg-indigo-950 dark:text-indigo-200 dark:hover:bg-indigo-700"
37- >
36+ <AlternateButton onClick={() => onCreateNewThread()}>
3837 <PlusIcon className="h-4 w-4" />
3938 New Thread
40- </button>
39+ </AlternateButton>
4140 {threads.length === 0 ? (
4241 <div className="px-3 py-2 text-neutral-600 dark:text-neutral-400">
4342 No threads yet
4443 </div>
4544 ) : (
4645 threads.map((thread) => (
47- <button
46+ <SecondaryButton
4847 key={thread.id}
4948 onClick={() => onThreadSelect(thread.id)}
50- className={`border-2 px-3 py-2 text-left hover:bg-neutral-300 dark:hover:bg-neutral-800 ${
51- currentThreadId === thread.id
52- ? "border-green-900 bg-neutral-300 dark:border-green-500 dark:bg-neutral-800"
53- : "border-transparent bg-neutral-100 dark:bg-neutral-950"
54- }`}
49+ isSelected={currentThreadId === thread.id}
5550 >
5651 <div className="line-clamp-2 break-words">
5752 {thread.title || `Thread ${thread.id}`}
5853 </div>
59- </button>
54+ </SecondaryButton>
6055 ))
6156 )}
6257 </div>
6358 {hasMoreThreads && (
64- <button
65- onClick={() => onLoadMore()}
66- className="flex items-center justify-center gap-1 bg-indigo-200 px-1 py-1 text-indigo-900 hover:bg-indigo-300 dark:bg-indigo-950 dark:text-indigo-200 dark:hover:bg-indigo-700"
67- >
59+ <AlternateButton onClick={() => onLoadMore()}>
6860 <ChevronDownIcon className="h-4 w-4" />
6961 Load More
70- </button>
62+ </AlternateButton>
7163 )}
7264 </div>
7365 <div className="flex flex-col gap-2">
src/components/buttons/AlternateButton.tsx+27−0
@@ -0,0 +1,27 @@
1+"use client";
2+
3+import type { ButtonHTMLAttributes, ReactNode } from "react";
4+
5+type AlternateButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
6+ children: ReactNode;
7+};
8+
9+// AlternateButton: A compact sidebar/action button using an alternate indigo color palette.
10+// Indigo-200 background with indigo-900 text for light mode, indigo-950 background with indigo-200 text for dark mode.
11+// Designed for sidebar action buttons that shouldn't use the primary project green.
12+// Slightly padded, with gentle color transitions on hover for accessible secondary actions.
13+export default function AlternateButton({
14+ children,
15+ className = "",
16+ ...props
17+}: AlternateButtonProps) {
18+ return (
19+ <button
20+ className={`flex items-center justify-center gap-1 bg-indigo-200 px-1 py-1 text-indigo-900 hover:bg-indigo-300 dark:bg-indigo-950 dark:text-indigo-200 dark:hover:bg-indigo-700 ${className}`}
21+ {...props}
22+ >
23+ {children}
24+ </button>
25+ );
26+}
27+
src/components/buttons/PrimaryButton.tsx+27−0
@@ -0,0 +1,27 @@
1+"use client";
2+
3+import type { ButtonHTMLAttributes, ReactNode } from "react";
4+
5+type PrimaryButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
6+ children: ReactNode;
7+};
8+
9+// PrimaryButton: Main action button (submit/send/etc.), styled with project primary color.
10+// Uses green-900 (light mode) and green-500 (dark mode) as background;
11+// white text in light mode, dark text in dark mode. Transitions to a lighter green on hover.
12+// Disabled state lowers opacity and disables cursor interaction.
13+export default function PrimaryButton({
14+ children,
15+ className = "",
16+ ...props
17+}: PrimaryButtonProps) {
18+ return (
19+ <button
20+ className={`bg-green-900 px-3 py-1 text-neutral-100 hover:bg-green-800 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-green-500 dark:text-neutral-900 dark:hover:bg-green-600 ${className}`}
21+ {...props}
22+ >
23+ {children}
24+ </button>
25+ );
26+}
27+
src/components/buttons/SecondaryButton.tsx+33−0
@@ -0,0 +1,33 @@
1+"use client";
2+
3+import type { ButtonHTMLAttributes, ReactNode } from "react";
4+
5+type SecondaryButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
6+ children: ReactNode;
7+ isSelected?: boolean;
8+};
9+
10+// SecondaryButton: A neutral, compact button styled for sidebar selections.
11+// When selected (isSelected=true), displays a green border and a neutral background.
12+// When not selected, uses neutral backgrounds and no border, maintaining visual simplicity.
13+// Designed to fit project style with neutral color palette and color-coded borders only on selection.
14+export default function SecondaryButton({
15+ children,
16+ isSelected = false,
17+ className = "",
18+ ...props
19+}: SecondaryButtonProps) {
20+ return (
21+ <button
22+ className={`border-2 px-3 py-2 text-left hover:bg-neutral-300 dark:hover:bg-neutral-800 ${
23+ isSelected
24+ ? "border-green-900 bg-neutral-300 dark:border-green-500 dark:bg-neutral-800"
25+ : "border-transparent bg-neutral-100 dark:bg-neutral-950"
26+ } ${className}`}
27+ {...props}
28+ >
29+ {children}
30+ </button>
31+ );
32+}
33+
src/hooks/useMessages.ts+103−0
@@ -0,0 +1,103 @@
1+import { useState, useEffect, useCallback } from "react";
2+import type { Message } from "@/src/lib/db/schema";
3+
4+export function useMessages(threadId: number | null) {
5+ const [messages, setMessages] = useState<Message[]>([]);
6+ const [isLoading, setIsLoading] = useState<boolean>(false);
7+
8+ const loadMessages = useCallback(async (id: number) => {
9+ try {
10+ const res = await fetch(`/api/threads/${id}/messages`);
11+ const data = await res.json();
12+ const loadedMessages = data.messages || [];
13+ setMessages(loadedMessages);
14+ } catch (error) {
15+ console.error("Failed to load messages", error);
16+ }
17+ }, []);
18+
19+ useEffect(() => {
20+ if (threadId !== null) {
21+ loadMessages(threadId);
22+ } else {
23+ setMessages([]);
24+ }
25+ }, [threadId, loadMessages]);
26+
27+ const sendMessage = async (
28+ message: string,
29+ currentThreadId: number | null,
30+ onCreateThread: (title?: string, firstMessage?: string) => Promise<number | null>,
31+ onThreadSelect: (id: number) => void,
32+ onThreadsReload: () => void
33+ ) => {
34+ if (!message.trim() || isLoading) return;
35+
36+ setIsLoading(true);
37+ let targetThreadId = currentThreadId;
38+
39+ if (!targetThreadId) {
40+ // Create a new thread if none exists
41+ targetThreadId = await onCreateThread(message.substring(0, 100), message);
42+ if (!targetThreadId) {
43+ setIsLoading(false);
44+ return;
45+ }
46+ onThreadSelect(targetThreadId);
47+ }
48+
49+ const userMsg: Message = {
50+ id: Date.now(),
51+ threadId: targetThreadId,
52+ role: "user",
53+ content: message,
54+ createdAt: new Date(),
55+ generationTimeMs: null,
56+ toolCalls: null,
57+ };
58+ setMessages((prev) => [...prev, userMsg]);
59+
60+ try {
61+ const res = await fetch("/api/chat", {
62+ method: "POST",
63+ headers: { "Content-Type": "application/json" },
64+ body: JSON.stringify({ message: message.trim(), threadId: targetThreadId }),
65+ });
66+
67+ const data = await res.json();
68+
69+ const botMsg: Message = {
70+ id: Date.now() + 1,
71+ threadId: targetThreadId,
72+ role: "assistant",
73+ content: data.answer || "",
74+ createdAt: new Date(),
75+ generationTimeMs: null,
76+ toolCalls: null,
77+ };
78+ setMessages((prev) => [...prev, botMsg]);
79+
80+ // Reload messages to get correct IDs from database
81+ await loadMessages(targetThreadId);
82+
83+ // Reload threads to update the order
84+ onThreadsReload();
85+ } catch (error) {
86+ console.error("Failed to send message", error);
87+ } finally {
88+ setIsLoading(false);
89+ }
90+ };
91+
92+ const clearMessages = () => {
93+ setMessages([]);
94+ };
95+
96+ return {
97+ messages,
98+ isLoading,
99+ sendMessage,
100+ clearMessages,
101+ };
102+}
103+
src/hooks/useThreadSelection.ts+40−0
@@ -0,0 +1,40 @@
1+import { useState, useEffect, useRef } from "react";
2+
3+export function useThreadSelection(
4+ onThreadSelect?: (threadId: number) => void,
5+ onThreadDeselect?: () => void
6+) {
7+ const [currentThreadId, setCurrentThreadId] = useState<number | null>(null);
8+ const messagesContainerRef = useRef<HTMLDivElement>(null);
9+
10+ useEffect(() => {
11+ // Scroll to top when a thread is selected
12+ if (currentThreadId !== null && messagesContainerRef.current) {
13+ messagesContainerRef.current.scrollTop = 0;
14+ }
15+ }, [currentThreadId]);
16+
17+ const selectThread = (threadId: number) => {
18+ setCurrentThreadId(threadId);
19+ if (onThreadSelect) {
20+ onThreadSelect(threadId);
21+ }
22+ };
23+
24+ const deselectThread = () => {
25+ setCurrentThreadId(null);
26+ if (onThreadDeselect) {
27+ onThreadDeselect();
28+ }
29+ };
30+
31+ return {
32+ currentThreadId,
33+ setCurrentThreadId,
34+ selectThread,
35+ deselectThread,
36+ messagesContainerRef,
37+ };
38+}
39+
40+
src/hooks/useThreads.ts+76−0
@@ -0,0 +1,76 @@
1+import { useState, useEffect } from "react";
2+import type { Thread } from "@/src/lib/db/schema";
3+
4+export function useThreads() {
5+ const [threads, setThreads] = useState<Thread[]>([]);
6+ const [totalThreadCount, setTotalThreadCount] = useState<number>(0);
7+ const [hasMoreThreads, setHasMoreThreads] = useState<boolean>(true);
8+
9+ const loadThreads = async (limit: number = 8) => {
10+ try {
11+ const res = await fetch(`/api/threads?limit=${limit}`);
12+ const data = await res.json();
13+ const threadsList = data.threads || [];
14+ setThreads(threadsList);
15+ setHasMoreThreads(data.hasMore || false);
16+ setTotalThreadCount(data.totalCount || 0);
17+ } catch (error) {
18+ console.error("Failed to load threads", error);
19+ }
20+ };
21+
22+ const loadMoreThreads = async (limit: number = 8) => {
23+ try {
24+ const offset = threads.length;
25+ const res = await fetch(`/api/threads?offset=${offset}&limit=${limit}`);
26+ const data = await res.json();
27+ const newThreads = data.threads || [];
28+ if (newThreads.length > 0) {
29+ setThreads((prev) => [...prev, ...newThreads]);
30+ setHasMoreThreads(data.hasMore || false);
31+ } else {
32+ setHasMoreThreads(false);
33+ }
34+ } catch (error) {
35+ console.error("Failed to load more threads", error);
36+ }
37+ };
38+
39+ const createThread = async (
40+ titleOverride?: string,
41+ firstMessage?: string
42+ ): Promise<number | null> => {
43+ try {
44+ const title = titleOverride || (firstMessage ? firstMessage.substring(0, 100) : "New Thread");
45+ const res = await fetch("/api/threads", {
46+ method: "POST",
47+ headers: { "Content-Type": "application/json" },
48+ body: JSON.stringify({ title }),
49+ });
50+ const data = await res.json();
51+ const newThread = data.thread;
52+
53+ // Reload threads to get the full list
54+ await loadThreads(8);
55+
56+ return newThread.id;
57+ } catch (error) {
58+ console.error("Failed to create thread", error);
59+ return null;
60+ }
61+ };
62+
63+ useEffect(() => {
64+ loadThreads(8);
65+ }, []);
66+
67+ return {
68+ threads,
69+ totalThreadCount,
70+ hasMoreThreads,
71+ loadThreads,
72+ loadMoreThreads,
73+ createThread,
74+ };
75+}
76+