@@ -3,13 +3,30 @@ import { useState, useEffect, useRef } from "react";
33 import ReactMarkdown from "react-markdown";
44 import remarkGfm from "remark-gfm";
55 import rehypeHighlight from "rehype-highlight";
6-import PaperPlaneIcon from "../src/components/icons/PaperPlaneIcon";
6+import PaperPlaneIcon from "@/src/components/icons/PaperPlaneIcon";
77 import "highlight.js/styles/nord.css";
88
9+type Thread = {
10+ id: number;
11+ title: string | null;
12+ createdAt: Date;
13+ updatedAt: Date;
14+};
15+
16+type Message = {
17+ id: number;
18+ threadId: number;
19+ role: string;
20+ content: string;
21+ createdAt: Date;
22+};
23+
924 export default function Home() {
10- const [messages, setMessages] = useState<{ role: string; content: string }[]>([]);
25+ const [messages, setMessages] = useState<Message[]>([]);
1126 const [input, setInput] = useState("");
1227 const [isDark, setIsDark] = useState(false);
28+ const [currentThreadId, setCurrentThreadId] = useState<number | null>(null);
29+ const [threads, setThreads] = useState<Thread[]>([]);
1330 const messagesEndRef = useRef<HTMLDivElement>(null);
1431 const messagesContainerRef = useRef<HTMLDivElement>(null);
1532
@@ -24,77 +41,25 @@ export default function Home() {
2441 }, []);
2542
2643 useEffect(() => {
27- const buildWelcomeMessage = async () => {
28- const parts: string[] = [];
29-
30- // User agent information
31- const userAgent = navigator.userAgent;
32- const platform = navigator.platform;
33- parts.push(`**User Agent:** ${userAgent}`);
34- parts.push(`**Platform:** ${platform}`);
35-
36- // Location information
37- if (navigator.geolocation) {
38- // Check permission state first if available
39- let permissionState = "unknown";
40- if (navigator.permissions) {
41- try {
42- const permission = await navigator.permissions.query({
43- name: "geolocation" as PermissionName,
44- });
45- permissionState = permission.state;
46- } catch (e) {
47- // Permissions API might not support geolocation query
48- }
49- }
44+ const loadThreads = async () => {
45+ try {
46+ const res = await fetch("/api/threads");
47+ const data = await res.json();
48+ const threadsList = data.threads || [];
49+ setThreads(threadsList);
5050
51- try {
52- const position = await new Promise<GeolocationPosition>((resolve, reject) => {
53- navigator.geolocation.getCurrentPosition(resolve, reject, {
54- timeout: 10000,
55- enableHighAccuracy: false,
56- maximumAge: 60000,
57- });
58- });
59- const { latitude, longitude } = position.coords;
60- parts.push(`**Location:** ${latitude.toFixed(4)}, ${longitude.toFixed(4)}`);
61- } catch (error: any) {
62- let errorMsg = "Unable to retrieve";
63- if (error?.code === 1) {
64- errorMsg =
65- permissionState === "prompt" ? "Permission prompt shown" : "Permission denied";
66- } else if (error?.code === 2) {
67- errorMsg = "Position unavailable";
68- } else if (error?.code === 3) {
69- errorMsg = "Request timeout";
70- } else if (error?.message) {
71- errorMsg = error.message;
72- }
73- parts.push(`**Location:** ${errorMsg} (permission: ${permissionState})`);
51+ // Load the most recent thread if available
52+ if (threadsList.length > 0) {
53+ const mostRecentThread = threadsList[0];
54+ setCurrentThreadId(mostRecentThread.id);
55+ await loadMessages(mostRecentThread.id);
7456 }
75- } else {
76- parts.push(`**Location:** Geolocation not supported`);
57+ } catch (error) {
58+ console.error("Failed to load threads", error);
7759 }
78-
79- // Local time
80- const now = new Date();
81- const timeString = now.toLocaleString(undefined, {
82- weekday: "long",
83- year: "numeric",
84- month: "long",
85- day: "numeric",
86- hour: "2-digit",
87- minute: "2-digit",
88- second: "2-digit",
89- timeZoneName: "short",
90- });
91- parts.push(`**Local Time:** ${timeString}`);
92-
93- const message = parts.join("\n\n");
94- setMessages([{ role: "assistant", content: message }]);
9560 };
9661
97- buildWelcomeMessage();
62+ loadThreads();
9863 }, []);
9964
10065 useEffect(() => {
@@ -121,45 +86,122 @@ export default function Home() {
12186 }
12287 };
12388
89+ const loadMessages = async (threadId: number) => {
90+ try {
91+ const res = await fetch(`/api/threads/${threadId}/messages`);
92+ const data = await res.json();
93+ setMessages(data.messages || []);
94+ } catch (error) {
95+ console.error("Failed to load messages", error);
96+ }
97+ };
98+
99+ const createNewThread = async () => {
100+ try {
101+ const res = await fetch("/api/threads", {
102+ method: "POST",
103+ headers: { "Content-Type": "application/json" },
104+ body: JSON.stringify({ title: "New Thread" }),
105+ });
106+ const data = await res.json();
107+ const newThread = data.thread;
108+ setCurrentThreadId(newThread.id);
109+ setMessages([]);
110+ // Reload threads to get the full list
111+ const threadsRes = await fetch("/api/threads");
112+ const threadsData = await threadsRes.json();
113+ setThreads(threadsData.threads || []);
114+ } catch (error) {
115+ console.error("Failed to create thread", error);
116+ }
117+ };
118+
119+ const handleThreadSelect = (threadId: number) => {
120+ setCurrentThreadId(threadId);
121+ loadMessages(threadId);
122+ };
123+
124124 const [historyIndex, setHistoryIndex] = useState<number | null>(null);
125125 const sendMessage = async (e: React.FormEvent) => {
126126 e.preventDefault();
127127 if (!input.trim()) return;
128128
129- const userMsg = { role: "user", content: input };
129+ let threadId = currentThreadId;
130+ if (!threadId) {
131+ // Create a new thread if none exists
132+ try {
133+ const res = await fetch("/api/threads", {
134+ method: "POST",
135+ headers: { "Content-Type": "application/json" },
136+ body: JSON.stringify({ title: input.substring(0, 50) }),
137+ });
138+ const data = await res.json();
139+ threadId = data.thread.id;
140+ setCurrentThreadId(threadId);
141+ setThreads((prev) => [data.thread, ...prev.slice(0, 9)]);
142+ } catch (error) {
143+ console.error("Failed to create thread", error);
144+ return;
145+ }
146+ }
147+
148+ const userMsg: Message = {
149+ id: Date.now(),
150+ threadId: threadId!,
151+ role: "user",
152+ content: input,
153+ createdAt: new Date(),
154+ };
130155 setMessages((prev) => [...prev, userMsg]);
156+ const inputValue = input;
131157 setInput("");
132158
133159 const res = await fetch("/api/chat", {
134160 method: "POST",
135161 headers: { "Content-Type": "application/json" },
136- body: JSON.stringify({ message: input }),
162+ body: JSON.stringify({ message: inputValue, threadId }),
137163 });
138164
139165 const data = await res.json();
140166
141- const botMsg = { role: "assistant", content: data.answer || "" };
167+ const botMsg: Message = {
168+ id: Date.now() + 1,
169+ threadId: threadId!,
170+ role: "assistant",
171+ content: data.answer || "",
172+ createdAt: new Date(),
173+ };
142174 setMessages((prev) => [...prev, botMsg]);
143175
176+ // Reload messages to get correct IDs from database
177+ await loadMessages(threadId!);
178+
179+ // Reload threads to update the order
180+ const threadsRes = await fetch("/api/threads");
181+ const threadsData = await threadsRes.json();
182+ setThreads(threadsData.threads || []);
183+
144184 setInput("");
145185 setHistoryIndex(null);
146186 };
147187 const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
148188 if (e.key === "ArrowUp") {
149189 e.preventDefault();
150- const idx = historyIndex ?? messages.length;
190+ const userMessages = messages.filter((m) => m.role === "user");
191+ const idx = historyIndex ?? userMessages.length;
151192 if (idx > 0) {
152193 const newIdx = idx - 1;
153194 setHistoryIndex(newIdx);
154- setInput(messages[newIdx].content);
195+ setInput(userMessages[newIdx].content);
155196 }
156197 } else if (e.key === "ArrowDown") {
157198 e.preventDefault();
158199 if (historyIndex !== null) {
200+ const userMessages = messages.filter((m) => m.role === "user");
159201 const newIdx = historyIndex + 1;
160- if (newIdx < messages.length) {
202+ if (newIdx < userMessages.length) {
161203 setHistoryIndex(newIdx);
162- setInput(messages[newIdx].content);
204+ setInput(userMessages[newIdx].content);
163205 } else {
164206 setHistoryIndex(null);
165207 setInput("");
@@ -176,19 +218,33 @@ export default function Home() {
176218 className="flex-1 overflow-y-auto overflow-x-hidden bg-slate-200 dark:bg-slate-900"
177219 >
178220 <div className="flex min-h-full flex-col justify-end">
179- {messages.map((msg, i) => (
180- <div key={i} className="min-w-0">
181- <div className="markdown-content m-2 bg-slate-300 p-2 text-slate-800 dark:bg-slate-950 dark:text-slate-200">
182- {msg.role === "assistant" ? (
183- <ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeHighlight]}>
184- {msg.content}
185- </ReactMarkdown>
186- ) : (
187- <div className="text-right">{msg.content}</div>
188- )}
221+ {threads.length === 0 && messages.length === 0 && currentThreadId === null ? (
222+ <div className="min-w-0">
223+ <div className="markdown-content m-1 p-1 bg-slate-300 text-slate-800 dark:bg-slate-950 dark:text-slate-200">
224+ <ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeHighlight]}>
225+ {`# Welcome! 👋
226+
227+I'm your personal assistant. To get started, click the **"New Thread"** button in the sidebar to create your first conversation thread.
228+
229+Once you've created a thread, you can start chatting with me by typing a message below.`}
230+ </ReactMarkdown>
189231 </div>
190232 </div>
191- ))}
233+ ) : (
234+ messages.map((msg) => (
235+ <div key={msg.id} className="min-w-0">
236+ <div className="markdown-content m-1 p-1 bg-slate-300 text-slate-800 dark:bg-slate-950 dark:text-slate-200">
237+ {msg.role === "assistant" ? (
238+ <ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeHighlight]}>
239+ {msg.content}
240+ </ReactMarkdown>
241+ ) : (
242+ <div className="text-right">{msg.content}</div>
243+ )}
244+ </div>
245+ </div>
246+ ))
247+ )}
192248 <div ref={messagesEndRef} />
193249 </div>
194250 </div>
@@ -210,20 +266,48 @@ export default function Home() {
210266 </form>
211267 </div>
212268 <div className="w-64 bg-slate-300 p-4 dark:bg-slate-950">
213- <div className="flex items-center justify-between">
214- <span>Dark Mode</span>
269+ <div className="flex flex-col gap-4">
215270 <button
216- onClick={toggleDarkMode}
217- className={`relative inline-flex h-6 w-11 items-center transition-colors ${
218- isDark ? "bg-indigo-500" : "bg-slate-400"
219- }`}
271+ onClick={createNewThread}
272+ className="bg-emerald-900 px-3 py-2 text-slate-100 hover:bg-emerald-800 dark:bg-emerald-500 dark:text-slate-900 dark:hover:bg-emerald-600"
220273 >
221- <span
222- className={`inline-block h-4 w-4 transform bg-slate-200 transition-transform dark:bg-slate-100 ${
223- isDark ? "translate-x-6" : "translate-x-1"
224- }`}
225- />
274+ New Thread
226275 </button>
276+ <div className="flex flex-col gap-2">
277+ <label className="text-sm font-semibold">Threads</label>
278+ <select
279+ value={currentThreadId || ""}
280+ onChange={(e) => {
281+ const threadId = e.target.value ? parseInt(e.target.value) : null;
282+ if (threadId) {
283+ handleThreadSelect(threadId);
284+ }
285+ }}
286+ className="bg-slate-200 px-2 py-1 text-slate-800 focus:outline-none dark:bg-slate-900 dark:text-slate-200"
287+ >
288+ <option value="">Select a thread...</option>
289+ {threads.map((thread) => (
290+ <option key={thread.id} value={thread.id}>
291+ {thread.title || `Thread ${thread.id}`}
292+ </option>
293+ ))}
294+ </select>
295+ </div>
296+ <div className="flex items-center justify-between">
297+ <span>Dark Mode</span>
298+ <button
299+ onClick={toggleDarkMode}
300+ className={`relative inline-flex h-6 w-11 items-center transition-colors ${
301+ isDark ? "bg-indigo-500" : "bg-slate-400"
302+ }`}
303+ >
304+ <span
305+ className={`inline-block h-4 w-4 transform bg-slate-200 transition-transform dark:bg-slate-100 ${
306+ isDark ? "translate-x-6" : "translate-x-1"
307+ }`}
308+ />
309+ </button>
310+ </div>
227311 </div>
228312 </div>
229313 </div>