@@ -4,7 +4,7 @@ import ReactMarkdown from "react-markdown";
44 import remarkGfm from "remark-gfm";
55 import rehypeHighlight from "rehype-highlight";
66 import PaperPlaneIcon from "@/src/components/icons/PaperPlaneIcon";
7-import "highlight.js/styles/nord.css";
7+import "./highlight-theme.css";
88
99 type Thread = {
1010 id: number;
@@ -29,8 +29,9 @@ export default function Home() {
2929 const [currentThreadId, setCurrentThreadId] = useState<number | null>(null);
3030 const [threads, setThreads] = useState<Thread[]>([]);
3131 const [isLoading, setIsLoading] = useState(false);
32- const messagesEndRef = useRef<HTMLDivElement>(null);
3332 const messagesContainerRef = useRef<HTMLDivElement>(null);
33+ const messageRefs = useRef<Map<number, HTMLDivElement>>(new Map());
34+ const prevMessagesLengthRef = useRef<number>(0);
3435
3536 const applyTheme = (mode: "device" | "dark" | "light") => {
3637 let shouldBeDark = false;
@@ -86,18 +87,22 @@ export default function Home() {
8687 }, []);
8788
8889 useEffect(() => {
89- if (messagesContainerRef.current) {
90- messagesContainerRef.current.scrollTop = messagesContainerRef.current.scrollHeight;
90+ // Scroll to the start of the newly added message
91+ if (messages.length > prevMessagesLengthRef.current) {
92+ const newMessage = messages[messages.length - 1];
93+ // Use requestAnimationFrame to ensure DOM has updated
94+ requestAnimationFrame(() => {
95+ const messageElement = messageRefs.current.get(newMessage.id);
96+ if (messageElement && messagesContainerRef.current) {
97+ const container = messagesContainerRef.current;
98+ const messageTop = messageElement.offsetTop;
99+ container.scrollTop = messageTop;
100+ }
101+ });
102+ prevMessagesLengthRef.current = messages.length;
91103 }
92104 }, [messages]);
93105
94- useEffect(() => {
95- // Initial scroll to bottom
96- if (messagesContainerRef.current) {
97- messagesContainerRef.current.scrollTop = messagesContainerRef.current.scrollHeight;
98- }
99- }, []);
100-
101106 const handleThemeChange = (mode: "device" | "dark" | "light") => {
102107 setThemeMode(mode);
103108 localStorage.setItem("themeMode", mode);
@@ -108,29 +113,35 @@ export default function Home() {
108113 try {
109114 const res = await fetch(`/api/threads/${threadId}/messages`);
110115 const data = await res.json();
111- setMessages(data.messages || []);
116+ const loadedMessages = data.messages || [];
117+ setMessages(loadedMessages);
118+ prevMessagesLengthRef.current = loadedMessages.length;
112119 } catch (error) {
113120 console.error("Failed to load messages", error);
114121 }
115122 };
116123
117- const createNewThread = async () => {
124+ const createNewThread = async (titleOverride?: string): Promise<number | null> => {
118125 try {
126+ const title = titleOverride || (input.trim() ? input.substring(0, 20) : "New Thread");
119127 const res = await fetch("/api/threads", {
120128 method: "POST",
121129 headers: { "Content-Type": "application/json" },
122- body: JSON.stringify({ title: "New Thread" }),
130+ body: JSON.stringify({ title }),
123131 });
124132 const data = await res.json();
125133 const newThread = data.thread;
126134 setCurrentThreadId(newThread.id);
127135 setMessages([]);
136+ prevMessagesLengthRef.current = 0;
128137 // Reload threads to get the full list
129138 const threadsRes = await fetch("/api/threads");
130139 const threadsData = await threadsRes.json();
131140 setThreads(threadsData.threads || []);
141+ return newThread.id;
132142 } catch (error) {
133143 console.error("Failed to create thread", error);
144+ return null;
134145 }
135146 };
136147
@@ -148,22 +159,8 @@ export default function Home() {
148159 let threadId = currentThreadId;
149160 if (!threadId) {
150161 // Create a new thread if none exists
151- try {
152- const res = await fetch("/api/threads", {
153- method: "POST",
154- headers: { "Content-Type": "application/json" },
155- body: JSON.stringify({ title: input.substring(0, 50) }),
156- });
157- const data = await res.json();
158- threadId = data.thread.id;
159- setCurrentThreadId(threadId);
160- setMessages([]);
161- // Reload threads to ensure UI is in sync
162- const threadsRes = await fetch("/api/threads");
163- const threadsData = await threadsRes.json();
164- setThreads(threadsData.threads || []);
165- } catch (error) {
166- console.error("Failed to create thread", error);
162+ threadId = await createNewThread(input.substring(0, 20));
163+ if (!threadId) {
167164 setIsLoading(false);
168165 return;
169166 }
@@ -218,9 +215,11 @@ export default function Home() {
218215 setHistoryIndex(null);
219216 };
220217 const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
218+ // Only cycle through user messages, not assistant messages
219+ const userMessages = messages.filter((m) => m.role === "user");
220+
221221 if (e.key === "ArrowUp") {
222222 e.preventDefault();
223- const userMessages = messages.filter((m) => m.role === "user");
224223 const idx = historyIndex ?? userMessages.length;
225224 if (idx > 0) {
226225 const newIdx = idx - 1;
@@ -230,7 +229,6 @@ export default function Home() {
230229 } else if (e.key === "ArrowDown") {
231230 e.preventDefault();
232231 if (historyIndex !== null) {
233- const userMessages = messages.filter((m) => m.role === "user");
234232 const newIdx = historyIndex + 1;
235233 if (newIdx < userMessages.length) {
236234 setHistoryIndex(newIdx);
@@ -259,9 +257,9 @@ export default function Home() {
259257 <div className="flex min-w-0 flex-1 flex-col">
260258 <div
261259 ref={messagesContainerRef}
262- className="text-sm pt-2 px-2 flex-1 overflow-y-auto overflow-x-hidden bg-stone-100 dark:bg-stone-950"
260+ className="text-sm p-4 flex-1 overflow-y-auto overflow-x-hidden bg-stone-100 dark:bg-stone-950"
263261 >
264- <div className="flex min-h-full flex-col justify-end gap-3">
262+ <div className="flex min-h-full flex-col justify-end gap-8">
265263 {threads.length === 0 && messages.length === 0 && currentThreadId === null ? (
266264 <div className="min-w-0">
267265 <div className="markdown-content p-1 bg-stone-200 text-stone-800 dark:bg-stone-900 dark:text-stone-200">
@@ -276,9 +274,19 @@ Once you've created a thread, you can start chatting with me by typing a message
276274 </div>
277275 ) : (
278276 messages.map((msg) => (
279- <div key={msg.id} className="min-w-0">
277+ <div
278+ key={msg.id}
279+ ref={(el) => {
280+ if (el) {
281+ messageRefs.current.set(msg.id, el);
282+ } else {
283+ messageRefs.current.delete(msg.id);
284+ }
285+ }}
286+ className="min-w-0"
287+ >
280288 <div
281- className={`markdown-content p-1 text-stone-800 dark:text-stone-200 ${
289+ className={`markdown-content p-2 text-stone-800 dark:text-stone-200 ${
282290 msg.role === "assistant"
283291 ? "bg-stone-200 dark:bg-stone-900"
284292 : "bg-stone-300 dark:bg-stone-800 text-right"
@@ -301,10 +309,9 @@ Once you've created a thread, you can start chatting with me by typing a message
301309 </div>
302310 ))
303311 )}
304- <div ref={messagesEndRef} />
305312 </div>
306313 </div>
307- <form onSubmit={sendMessage} className="flex">
314+ <form onSubmit={sendMessage} className="flex shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.1),0_-2px_4px_-1px_rgba(0,0,0,0.06)] dark:shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.3),0_-2px_4px_-1px_rgba(0,0,0,0.2)]">
308315 <input
309316 type="text"
310317 value={input}
@@ -324,9 +331,9 @@ Once you've created a thread, you can start chatting with me by typing a message
324331 </form>
325332 </div>
326333 <div className="w-64 bg-stone-200 p-1 dark:bg-stone-900">
327- <div className="flex flex-col gap-2">
334+ <div className="flex flex-col gap-2 p-4">
328335 <button
329- onClick={createNewThread}
336+ onClick={() => createNewThread()}
330337 className="bg-green-900 px-1 py-1 text-stone-100 hover:bg-green-800 dark:bg-green-500 dark:text-stone-900 dark:hover:bg-green-600"
331338 >
332339 New Thread
@@ -341,7 +348,7 @@ Once you've created a thread, you can start chatting with me by typing a message
341348 handleThreadSelect(threadId);
342349 }
343350 }}
344- className="bg-stone-100 px-1 py-1 text-stone-800 focus:outline-none dark:bg-stone-950 dark:text-stone-200"
351+ className="bg-stone-100 px-3 py-1 text-stone-800 focus:outline-none dark:bg-stone-950 dark:text-stone-200"
345352 >
346353 <option value="">Select a thread...</option>
347354 {threads.map((thread) => (
@@ -356,7 +363,7 @@ Once you've created a thread, you can start chatting with me by typing a message
356363 <select
357364 value={themeMode}
358365 onChange={(e) => handleThemeChange(e.target.value as "device" | "dark" | "light")}
359- className="bg-stone-100 px-1 py-1 text-stone-800 focus:outline-none dark:bg-stone-950 dark:text-stone-200"
366+ className="bg-stone-100 px-3 py-1 text-stone-800 focus:outline-none dark:bg-stone-950 dark:text-stone-200"
360367 >
361368 <option value="device">Device</option>
362369 <option value="dark">Dark</option>