xonecas.io
53129
Pa

PAT / commit f53eb41

feat: threads UI and api

xonecas2025-12-16 f53eb4185e7769d0c86746d9824fc4227508dcba parent 14b407d

11 files changed

.cursorignore+1−0
@@ -1,3 +1,4 @@
11 node_modules
22 .next
33 .env
4+data/
.gitignore+1−0
@@ -1,3 +1,4 @@
11 node_modules
22 .next
33 .env
4+data/
.prettierignore+1−1
@@ -6,4 +6,4 @@ build
66 *.min.js
77 *.min.css
88 drizzle
9-
9+data/
AGENTS.md+3−2
@@ -112,10 +112,11 @@ Agents MUST use only these existing dependencies. Do NOT add new dependencies wi
112112 - Optional: Add file path comments at the top of library files (e.g., `/* personal-assistant-thing/src/lib/ollama.ts */`)
113113
114114 10. **Imports**:
115- - Use relative imports for local files (e.g., `import PaperPlaneIcon from "../src/components/icons/PaperPlaneIcon"`)
115+ - Use absolute imports with `@/` prefix for local files (e.g., `import PaperPlaneIcon from "@/src/components/icons/PaperPlaneIcon"`)
116116 - Group imports: external packages first, then local imports
117117 - Use named imports from libraries (e.g., `import { NextResponse } from "next/server"`)
118- - Use default imports for component files (e.g., `import PaperPlaneIcon from "../src/components/icons/PaperPlaneIcon"`)
118+ - Use default imports for component files (e.g., `import PaperPlaneIcon from "@/src/components/icons/PaperPlaneIcon"`)
119+ - Path alias `@/` is configured in `tsconfig.json` to point to the project root
119120
120121 ## Project Structure
121122
TODO.md+10−0
@@ -9,3 +9,13 @@
99
1010 - Text input, we should be able to press a button and record a prompt.
1111 - Text to voice, we should have a button to have the models replies be read with text to voice.
12+
13+
14+## Refactor Appearence:
15+
16+- Change Primary color to `green-500` for dark mode and `green-900` for light mode.
17+- Change all background and text colors to use `stone` shades
18+- Containers should use background color `stone-950` for dark mode and `stone-100` for light mode
19+- Child components should use background color `stone-900` for dark mode and `stone-200` for light mode
20+- Maximum margin should be 1
21+- Maximum padding should be 1
app/api/chat/route.ts+39−5
@@ -1,22 +1,56 @@
11 import { NextResponse } from "next/server";
2-import { fetchOllamaResponse } from "../../../src/lib/ollama";
3-import { fetchDuckDuckGo } from "../../../src/lib/duckduckgo";
2+import { fetchOllamaResponse } from "@/src/lib/ollama";
3+import { fetchDuckDuckGo } from "@/src/lib/duckduckgo";
4+import { db } from "@/src/lib/db";
5+import { messages, threads } from "@/src/lib/db/schema";
6+import { eq } from "drizzle-orm";
47
58 export async function POST(request: Request) {
6- const { message } = await request.json();
9+ const { message, threadId } = await request.json();
10+
11+ if (!threadId) {
12+ return NextResponse.json({ error: "threadId is required" }, { status: 400 });
13+ }
714
815 try {
9- // 1. Search DuckDuckGo
16+ // 1. Store user message
17+ const userMessage = await db
18+ .insert(messages)
19+ .values({
20+ threadId: parseInt(threadId),
21+ role: "user",
22+ content: message,
23+ createdAt: new Date(),
24+ })
25+ .returning();
26+
27+ // 2. Search DuckDuckGo
1028 const searchResults = await fetchDuckDuckGo(message);
1129
1230 console.debug("searchResults:", searchResults);
1331
14- // 2. Build prompt
32+ // 3. Build prompt
1533 const prompt = `${message}\n\nRelevant info from DuckDuckGo: ${JSON.stringify(
1634 searchResults
1735 )}\n\nAssistant:`;
1836
37+ // 4. Get assistant response
1938 const answer = await fetchOllamaResponse(prompt);
39+
40+ // 5. Store assistant message
41+ await db.insert(messages).values({
42+ threadId: parseInt(threadId),
43+ role: "assistant",
44+ content: answer,
45+ createdAt: new Date(),
46+ });
47+
48+ // 6. Update thread's updatedAt timestamp
49+ await db
50+ .update(threads)
51+ .set({ updatedAt: new Date() })
52+ .where(eq(threads.id, parseInt(threadId)));
53+
2054 return NextResponse.json({ answer });
2155 } catch (error) {
2256 console.error("Chat API error", error);
app/api/threads/[id]/messages/route.ts+29−0
@@ -0,0 +1,29 @@
1+import { NextResponse } from "next/server";
2+import { db } from "@/src/lib/db";
3+import { messages } from "@/src/lib/db/schema";
4+import { eq, asc } from "drizzle-orm";
5+
6+export async function GET(
7+ request: Request,
8+ { params }: { params: Promise<{ id: string }> }
9+) {
10+ try {
11+ const { id } = await params;
12+ const threadId = parseInt(id);
13+ if (isNaN(threadId)) {
14+ return NextResponse.json({ error: "Invalid thread ID" }, { status: 400 });
15+ }
16+
17+ const messagesList = await db
18+ .select()
19+ .from(messages)
20+ .where(eq(messages.threadId, threadId))
21+ .orderBy(asc(messages.createdAt));
22+
23+ return NextResponse.json({ messages: messagesList });
24+ } catch (error) {
25+ console.error("Get messages error", error);
26+ return NextResponse.json({ error: "Failed to get messages" }, { status: 500 });
27+ }
28+}
29+
app/api/threads/route.ts+39−0
@@ -0,0 +1,39 @@
1+import { NextResponse } from "next/server";
2+import { db } from "@/src/lib/db";
3+import { threads } from "@/src/lib/db/schema";
4+import { desc } from "drizzle-orm";
5+
6+export async function POST(request: Request) {
7+ try {
8+ const { title } = await request.json();
9+ const newThread = await db
10+ .insert(threads)
11+ .values({
12+ title: title || "New Thread",
13+ createdAt: new Date(),
14+ updatedAt: new Date(),
15+ })
16+ .returning();
17+
18+ return NextResponse.json({ thread: newThread[0] });
19+ } catch (error) {
20+ console.error("Create thread error", error);
21+ return NextResponse.json({ error: "Failed to create thread" }, { status: 500 });
22+ }
23+}
24+
25+export async function GET() {
26+ try {
27+ const threadsList = await db
28+ .select()
29+ .from(threads)
30+ .orderBy(desc(threads.updatedAt))
31+ .limit(10);
32+
33+ return NextResponse.json({ threads: threadsList });
34+ } catch (error) {
35+ console.error("Get threads error", error);
36+ return NextResponse.json({ error: "Failed to get threads" }, { status: 500 });
37+ }
38+}
39+
app/globals.css+5−5
@@ -12,7 +12,7 @@
1212 .markdown-content h4,
1313 .markdown-content h5,
1414 .markdown-content h6 {
15- @apply mb-2 mt-4 font-bold;
15+ @apply mb-1 font-bold;
1616 }
1717
1818 .markdown-content h1 {
@@ -28,12 +28,12 @@
2828 }
2929
3030 .markdown-content p {
31- @apply mb-2;
31+ @apply mb-1;
3232 }
3333
3434 .markdown-content ul,
3535 .markdown-content ol {
36- @apply mb-2 ml-6;
36+ @apply mb-1 ml-6;
3737 }
3838
3939 .markdown-content ul {
@@ -57,7 +57,7 @@
5757 }
5858
5959 .markdown-content table {
60- @apply mb-2 border-collapse border border-slate-500 dark:border-slate-400;
60+ @apply mb-1 border-collapse border border-slate-500 dark:border-slate-400;
6161 }
6262
6363 .markdown-content th,
@@ -71,5 +71,5 @@
7171
7272 /* Code block styling */
7373 .markdown-content pre {
74- @apply mb-2 overflow-x-auto p-3;
74+ @apply mb-1 overflow-x-auto p-3;
7575 }
app/page.tsx+181−97
@@ -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>
tsconfig.json+4−1
@@ -17,7 +17,10 @@
1717 {
1818 "name": "next"
1919 }
20- ]
20+ ],
21+ "paths": {
22+ "@/*": ["./*"]
23+ }
2124 },
2225 "include": [
2326 "next-env.d.ts",