xonecas.io
53129
Pa

PAT / commit 0430706

feat: error handling

xonecas2025-12-18 0430706fa18e3e0d1f7dc0cfb027a57756902e0a parent dd4f14a

20 files changed

AGENTS.md+0−1
@@ -73,7 +73,6 @@ Add tests when prompted only.
7373 - Prettier automatically sorts Tailwind CSS classes via `prettier-plugin-tailwindcss`
7474
7575 8. **Error Handling**:
76- - Use `console.error` for errors
7776 - Use `lib/debug` for debug information
7877 - Return user-friendly error messages in API responses
7978 - Handle API errors gracefully with try/catch blocks
app/api/chat/route.ts+0−2
@@ -242,7 +242,6 @@ export async function POST(request: Request) {
242242 safeClose();
243243 }
244244 } catch (error) {
245- console.error("Chat API error", error);
246245 if (!isControllerClosed) {
247246 try {
248247 controller.enqueue(
@@ -267,7 +266,6 @@ export async function POST(request: Request) {
267266 },
268267 });
269268 } catch (error) {
270- console.error("Chat API error", error);
271269 return NextResponse.json({ answer: "Sorry, something went wrong." }, { status: 500 });
272270 }
273271 }
app/api/models/route.ts+0−1
@@ -34,7 +34,6 @@ export async function GET() {
3434 }));
3535 return NextResponse.json({ models });
3636 } catch (error) {
37- console.error("Failed to fetch models", error);
3837 return NextResponse.json({ error: "Failed to fetch models" }, { status: 500 });
3938 }
4039 }
app/api/settings/route.ts+0−2
@@ -15,7 +15,6 @@ export async function GET() {
1515 settings: settings || { maxPromptLength: "none", selectedModel: "gpt-oss" },
1616 });
1717 } catch (error) {
18- console.error("Get settings error", error);
1918 return NextResponse.json({ error: "Failed to get settings" }, { status: 500 });
2019 }
2120 }
@@ -53,7 +52,6 @@ export async function POST(request: Request) {
5352
5453 return NextResponse.json({ settings: mergedSettings });
5554 } catch (error) {
56- console.error("Set settings error", error);
5755 return NextResponse.json({ error: "Failed to set settings" }, { status: 500 });
5856 }
5957 }
app/api/threads/[id]/messages/[messageId]/route.ts+0−1
@@ -31,7 +31,6 @@ export async function DELETE(
3131
3232 return NextResponse.json({ success: true });
3333 } catch (error) {
34- console.error("Delete message error", error);
3534 return NextResponse.json({ error: "Failed to delete message" }, { status: 500 });
3635 }
3736 }
app/api/threads/[id]/messages/route.ts+0−1
@@ -19,7 +19,6 @@ export async function GET(request: Request, { params }: { params: Promise<{ id:
1919
2020 return NextResponse.json({ messages: messagesList });
2121 } catch (error) {
22- console.error("Get messages error", error);
2322 return NextResponse.json({ error: "Failed to get messages" }, { status: 500 });
2423 }
2524 }
app/api/threads/[id]/route.ts+0−2
@@ -39,7 +39,6 @@ export async function PATCH(request: Request, { params }: { params: Promise<{ id
3939
4040 return NextResponse.json({ thread: updatedThread[0] });
4141 } catch (error) {
42- console.error("Update thread error", error);
4342 return NextResponse.json({ error: "Failed to update thread" }, { status: 500 });
4443 }
4544 }
@@ -61,7 +60,6 @@ export async function DELETE(request: Request, { params }: { params: Promise<{ i
6160
6261 return NextResponse.json({ success: true });
6362 } catch (error) {
64- console.error("Delete thread error", error);
6563 return NextResponse.json({ error: "Failed to delete thread" }, { status: 500 });
6664 }
6765 }
app/api/threads/route.ts+0−2
@@ -34,7 +34,6 @@ export async function POST(request: Request) {
3434
3535 return NextResponse.json({ thread: newThread[0] });
3636 } catch (error) {
37- console.error("Create thread error", error);
3837 return NextResponse.json({ error: "Failed to create thread" }, { status: 500 });
3938 }
4039 }
@@ -58,7 +57,6 @@ export async function GET(request: Request) {
5857
5958 return NextResponse.json({ threads: threadsList, hasMore, totalCount });
6059 } catch (error) {
61- console.error("Get threads error", error);
6260 return NextResponse.json({ error: "Failed to get threads" }, { status: 500 });
6361 }
6462 }
app/page.tsx+59−22
@@ -1,5 +1,5 @@
11 "use client";
2-import { useRef } from "react";
2+import { useRef, useState, useEffect } from "react";
33 import Sidebar from "@/src/components/Sidebar";
44 import MessageInput, { type MessageInputRef } from "@/src/components/MessageInput";
55 import MessageList from "@/src/components/MessageList";
@@ -12,9 +12,10 @@ import { useThreadSelection } from "@/src/hooks/useThreadSelection";
1212 import "./highlight-theme.css";
1313
1414 export default function Home() {
15+ const [error, setError] = useState<string | null>(null);
1516 const { themeMode, handleThemeChange } = useTheme();
1617 const { selectedModel, handleModelChange, maxPromptLength, handleMaxPromptLengthChange } =
17- useModelSettings();
18+ useModelSettings(setError);
1819 const {
1920 threads,
2021 totalThreadCount,
@@ -35,10 +36,29 @@ export default function Home() {
3536 sendMessage,
3637 clearMessages,
3738 stopGeneration,
38- deleteMessage,
39- } = useMessages(currentThreadId);
39+ deleteMessage: deleteMessageInternal,
40+ } = useMessages(currentThreadId, setError);
4041 const messageInputRef = useRef<MessageInputRef>(null);
4142
43+ const handleDeleteMessage = (messageId: number, threadId: number) => {
44+ deleteMessageInternal(messageId, threadId, setError);
45+ };
46+
47+ // Clear error when thread changes
48+ useEffect(() => {
49+ setError(null);
50+ }, [currentThreadId]);
51+
52+ // Auto-dismiss error after 3 seconds
53+ useEffect(() => {
54+ if (error) {
55+ const timer = setTimeout(() => {
56+ setError(null);
57+ }, 3000);
58+ return () => clearTimeout(timer);
59+ }
60+ }, [error]);
61+
4262 const handleThreadSelect = (threadId: number) => {
4363 selectThread(threadId);
4464 };
@@ -46,6 +66,7 @@ export default function Home() {
4666 const handleCreateNewThread = () => {
4767 deselectThread();
4868 clearMessages();
69+ setError(null);
4970 // Focus the input after a short delay to ensure DOM has updated
5071 setTimeout(() => {
5172 messageInputRef.current?.focus();
@@ -56,40 +77,53 @@ export default function Home() {
5677 threadId: number,
5778 updates: { model?: string; maxPromptLength?: "none" | 1024 | 4096 | null }
5879 ) => {
80+ setError(null);
5981 try {
60- await updateThread(threadId, updates);
82+ await updateThread(threadId, updates, setError);
6183 // Reload threads to ensure UI is in sync
62- await loadThreads(8);
84+ await loadThreads(8, setError);
6385 } catch (error) {
64- console.error("Failed to update thread", error);
65- throw error;
86+ if (error instanceof Error) {
87+ setError(error.message);
88+ }
6689 }
6790 };
6891
6992 const handleThreadDelete = async (threadId: number) => {
93+ setError(null);
7094 try {
71- await deleteThread(threadId);
95+ await deleteThread(threadId, setError);
7296 // If the deleted thread was the current thread, deselect it
7397 if (currentThreadId === threadId) {
7498 deselectThread();
7599 clearMessages();
76100 }
77101 } catch (error) {
78- console.error("Failed to delete thread", error);
79- throw error;
102+ if (error instanceof Error) {
103+ setError(error.message);
104+ }
80105 }
81106 };
82107
83108 const handleSendMessage = async (message: string) => {
84- await sendMessage(
85- message,
86- currentThreadId,
87- createThread,
88- selectThread,
89- loadThreads,
90- selectedModel,
91- maxPromptLength
92- );
109+ setError(null);
110+ try {
111+ await sendMessage(
112+ message,
113+ currentThreadId,
114+ (title, firstMessage, model, maxPromptLength) =>
115+ createThread(title, firstMessage, model, maxPromptLength, setError),
116+ selectThread,
117+ () => loadThreads(8, setError),
118+ selectedModel,
119+ maxPromptLength,
120+ setError
121+ );
122+ } catch (error) {
123+ if (error instanceof Error) {
124+ setError(error.message);
125+ }
126+ }
93127 };
94128
95129 // Get the model name for the current thread, or use selected model if no thread
@@ -117,13 +151,14 @@ export default function Home() {
117151 onModelChange={handleModelChange}
118152 maxPromptLength={maxPromptLength}
119153 onMaxPromptLengthChange={handleMaxPromptLengthChange}
154+ onError={setError}
120155 />
121156 ) : (
122157 <MessageList
123158 messages={messages}
124159 streamingMessageId={streamingMessageId}
125160 threadId={currentThreadId}
126- onDeleteMessage={deleteMessage}
161+ onDeleteMessage={handleDeleteMessage}
127162 />
128163 )}
129164 </div>
@@ -137,12 +172,14 @@ export default function Home() {
137172 modelName={currentModelName}
138173 isStreaming={isLoading && streamingMessageId !== null}
139174 onStop={stopGeneration}
175+ error={error}
140176 currentThreadId={currentThreadId}
141177 currentThread={
142178 currentThreadId !== null ? threads.find((t) => t.id === currentThreadId) || null : null
143179 }
144180 onThreadUpdate={handleThreadUpdate}
145181 onThreadDelete={handleThreadDelete}
182+ onError={setError}
146183 />
147184 </div>
148185 <Sidebar
@@ -152,7 +189,7 @@ export default function Home() {
152189 onCreateNewThread={handleCreateNewThread}
153190 onThreadSelect={handleThreadSelect}
154191 onThemeChange={handleThemeChange}
155- onLoadMore={loadMoreThreads}
192+ onLoadMore={(limit) => loadMoreThreads(limit, setError)}
156193 hasMoreThreads={hasMoreThreads}
157194 />
158195 </div>
src/components/DeleteThreadButton.tsx+5−1
@@ -8,12 +8,14 @@ type DeleteThreadButtonProps = {
88 threadId: number;
99 threadTitle: string;
1010 onDeleteThread: (threadId: number) => void;
11+ onError?: (error: string) => void;
1112 };
1213
1314 export default function DeleteThreadButton({
1415 threadId,
1516 threadTitle,
1617 onDeleteThread,
18+ onError,
1719 }: DeleteThreadButtonProps) {
1820 const [isModalOpen, setIsModalOpen] = useState(false);
1921 const [isDeleting, setIsDeleting] = useState(false);
@@ -24,7 +26,9 @@ export default function DeleteThreadButton({
2426 await onDeleteThread(threadId);
2527 setIsModalOpen(false);
2628 } catch (error) {
27- console.error("Failed to delete thread", error);
29+ if (onError && error instanceof Error) {
30+ onError(error.message);
31+ }
2832 } finally {
2933 setIsDeleting(false);
3034 }
src/components/MessageInput.tsx+31−22
@@ -5,6 +5,7 @@ import PaperPlaneIcon from "@/src/components/icons/PaperPlaneIcon";
55 import PrimaryButton from "@/src/components/buttons/PrimaryButton";
66 import ThinkingNotification from "@/src/components/ThinkingNotification";
77 import ThreadSettingsButton from "@/src/components/ThreadSettingsButton";
8+import ErrorNotification from "@/src/components/ErrorNotification";
89 import type { Message } from "@/src/lib/db/schema";
910 import type { Thread } from "@/src/lib/db/schema";
1011
@@ -16,6 +17,7 @@ type MessageInputProps = {
1617 modelName?: string;
1718 isStreaming?: boolean;
1819 onStop?: () => void;
20+ error?: string | null;
1921 currentThreadId: number | null;
2022 currentThread: Thread | null;
2123 onThreadUpdate?: (
@@ -23,6 +25,7 @@ type MessageInputProps = {
2325 updates: { model?: string; maxPromptLength?: "none" | 1024 | 4096 | null }
2426 ) => Promise<void>;
2527 onThreadDelete?: (threadId: number) => Promise<void>;
28+ onError?: (error: string) => void;
2629 };
2730
2831 export type MessageInputRef = {
@@ -30,22 +33,24 @@ export type MessageInputRef = {
3033 };
3134
3235 const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
33- (
34- {
35- isLoading,
36- isLoadingMessages,
37- messages,
38- onSubmit,
39- modelName = "gpt-oss",
40- isStreaming = false,
41- onStop,
42- currentThreadId,
43- currentThread,
44- onThreadUpdate,
45- onThreadDelete,
46- },
47- ref
48- ) => {
36+ (
37+ {
38+ isLoading,
39+ isLoadingMessages,
40+ messages,
41+ onSubmit,
42+ modelName = "gpt-oss",
43+ isStreaming = false,
44+ onStop,
45+ error,
46+ currentThreadId,
47+ currentThread,
48+ onThreadUpdate,
49+ onThreadDelete,
50+ onError,
51+ },
52+ ref
53+ ) => {
4954 const [input, setInput] = useState("");
5055 const [historyIndex, setHistoryIndex] = useState<number | null>(null);
5156 const textareaRef = useRef<HTMLTextAreaElement>(null);
@@ -142,19 +147,23 @@ const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
142147 return (
143148 <div className="pointer-events-none absolute bottom-0 left-0 right-0 z-10 flex justify-center p-1">
144149 <div className="pointer-events-auto m-4 w-full max-w-5xl">
145- <div className="mb-2 flex items-start justify-between gap-2">
146- <div className="flex-1">
150+ <div className="mb-2 grid grid-cols-3 items-start gap-2">
151+ <div className="flex items-center">
147152 {isStreaming && onStop && <ThinkingNotification onStop={onStop} />}
148153 </div>
149- {currentThreadId !== null && currentThread && onThreadUpdate && onThreadDelete && (
150- <div className="flex-shrink-0">
154+ <div className="flex items-center justify-center">
155+ {error && <ErrorNotification message={error} />}
156+ </div>
157+ <div className="flex items-center justify-end">
158+ {currentThreadId !== null && currentThread && onThreadUpdate && onThreadDelete && (
151159 <ThreadSettingsButton
152160 thread={currentThread}
153161 onUpdateThread={onThreadUpdate}
154162 onDeleteThread={onThreadDelete}
163+ onError={onError}
155164 />
156- </div>
157- )}
165+ )}
166+ </div>
158167 </div>
159168 <form
160169 onSubmit={handleSubmit}
src/components/NoThreadSelected.tsx+15−3
@@ -8,6 +8,7 @@ type NoThreadSelectedProps = {
88 onModelChange: (model: string) => void;
99 maxPromptLength: "none" | 1024 | 4096;
1010 onMaxPromptLengthChange: (value: "none" | 1024 | 4096) => void;
11+ onError?: (error: string) => void;
1112 };
1213
1314 export default function NoThreadSelected({
@@ -16,6 +17,7 @@ export default function NoThreadSelected({
1617 onModelChange,
1718 maxPromptLength,
1819 onMaxPromptLengthChange,
20+ onError,
1921 }: NoThreadSelectedProps) {
2022 const [currentTime, setCurrentTime] = useState<Date | null>(null);
2123 const [models, setModels] = useState<Array<{ name: string; model: string }>>([]);
@@ -34,17 +36,27 @@ export default function NoThreadSelected({
3436 useEffect(() => {
3537 setIsLoadingModels(true);
3638 fetch("/api/models")
37- .then((res) => res.json())
39+ .then(async (res) => {
40+ if (!res.ok) {
41+ const errorData = await res.json().catch((parseError) => {
42+ throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
43+ });
44+ throw new Error(errorData.error || res.statusText);
45+ }
46+ return res.json();
47+ })
3848 .then((data) => {
3949 const availableModels = data.models || [];
4050 setModels(availableModels);
4151 setIsLoadingModels(false);
4252 })
4353 .catch((error) => {
44- console.error("Failed to load models", error);
4554 setIsLoadingModels(false);
55+ if (onError && error instanceof Error) {
56+ onError(error.message);
57+ }
4658 });
47- }, []);
59+ }, [onError]);
4860
4961 const formatTime = (date: Date): string => {
5062 return date.toLocaleString();
src/components/ThreadSettingsButton.tsx+3−0
@@ -12,12 +12,14 @@ type ThreadSettingsButtonProps = {
1212 updates: { model?: string; maxPromptLength?: "none" | 1024 | 4096 | null }
1313 ) => Promise<void>;
1414 onDeleteThread: (threadId: number) => Promise<void>;
15+ onError?: (error: string) => void;
1516 };
1617
1718 export default function ThreadSettingsButton({
1819 thread,
1920 onUpdateThread,
2021 onDeleteThread,
22+ onError,
2123 }: ThreadSettingsButtonProps) {
2224 const [isModalOpen, setIsModalOpen] = useState(false);
2325
@@ -41,6 +43,7 @@ export default function ThreadSettingsButton({
4143 thread={thread}
4244 onUpdateThread={onUpdateThread}
4345 onDeleteThread={onDeleteThread}
46+ onError={onError}
4447 />
4548 </>
4649 );
src/components/ThreadSettingsModal.tsx+20−4
@@ -16,6 +16,7 @@ type ThreadSettingsModalProps = {
1616 updates: { model?: string; maxPromptLength?: "none" | 1024 | 4096 | null }
1717 ) => Promise<void>;
1818 onDeleteThread: (threadId: number) => Promise<void>;
19+ onError?: (error: string) => void;
1920 };
2021
2122 export default function ThreadSettingsModal({
@@ -24,6 +25,7 @@ export default function ThreadSettingsModal({
2425 thread,
2526 onUpdateThread,
2627 onDeleteThread,
28+ onError,
2729 }: ThreadSettingsModalProps) {
2830 const [models, setModels] = useState<Array<{ name: string; model: string }>>([]);
2931 const [isLoadingModels, setIsLoadingModels] = useState(false);
@@ -37,15 +39,25 @@ export default function ThreadSettingsModal({
3739 if (isOpen) {
3840 setIsLoadingModels(true);
3941 fetch("/api/models")
40- .then((res) => res.json())
42+ .then(async (res) => {
43+ if (!res.ok) {
44+ const errorData = await res.json().catch((parseError) => {
45+ throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
46+ });
47+ throw new Error(errorData.error || res.statusText);
48+ }
49+ return res.json();
50+ })
4151 .then((data) => {
4252 const availableModels = data.models || [];
4353 setModels(availableModels);
4454 setIsLoadingModels(false);
4555 })
4656 .catch((error) => {
47- console.error("Failed to load models", error);
4857 setIsLoadingModels(false);
58+ if (onError && error instanceof Error) {
59+ onError(error.message);
60+ }
4961 });
5062 }
5163 }, [isOpen]);
@@ -82,7 +94,9 @@ export default function ThreadSettingsModal({
8294 });
8395 onClose();
8496 } catch (error) {
85- console.error("Failed to update thread settings", error);
97+ if (onError && error instanceof Error) {
98+ onError(error.message);
99+ }
86100 } finally {
87101 setIsSaving(false);
88102 }
@@ -96,7 +110,9 @@ export default function ThreadSettingsModal({
96110 await onDeleteThread(thread.id);
97111 onClose();
98112 } catch (error) {
99- console.error("Failed to delete thread", error);
113+ if (onError && error instanceof Error) {
114+ onError(error.message);
115+ }
100116 } finally {
101117 setIsDeleting(false);
102118 }
src/hooks/useMessages.ts+70−36
@@ -1,7 +1,7 @@
11 import { useState, useEffect, useCallback, useRef } from "react";
22 import type { Message } from "@/src/lib/db/schema";
33
4-export function useMessages(threadId: number | null) {
4+export function useMessages(threadId: number | null, onError?: (error: string) => void) {
55 const [messages, setMessages] = useState<Message[]>([]);
66 const [isLoading, setIsLoading] = useState<boolean>(false);
77 const [isLoadingMessages, setIsLoadingMessages] = useState<boolean>(false);
@@ -9,31 +9,39 @@ export function useMessages(threadId: number | null) {
99 const sendingToThreadIdRef = useRef<number | null>(null);
1010 const abortControllerRef = useRef<AbortController | null>(null);
1111
12- const loadMessages = useCallback(async (id: number) => {
13- setIsLoadingMessages(true);
14- try {
15- const res = await fetch(`/api/threads/${id}/messages`);
16- const data = await res.json();
17- const loadedMessages = data.messages || [];
18- setMessages(loadedMessages);
19- } catch (error) {
20- console.error("Failed to load messages", error);
21- } finally {
22- setIsLoadingMessages(false);
23- }
24- }, []);
12+ const loadMessages = useCallback(
13+ async (id: number, onError?: (error: string) => void) => {
14+ setIsLoadingMessages(true);
15+ try {
16+ const res = await fetch(`/api/threads/${id}/messages`);
17+ if (!res.ok) {
18+ throw new Error(`Failed to load messages: ${res.status}`);
19+ }
20+ const data = await res.json();
21+ const loadedMessages = data.messages || [];
22+ setMessages(loadedMessages);
23+ } catch (error) {
24+ if (onError && error instanceof Error) {
25+ onError(error.message);
26+ }
27+ } finally {
28+ setIsLoadingMessages(false);
29+ }
30+ },
31+ []
32+ );
2533
2634 useEffect(() => {
2735 if (threadId !== null) {
2836 // Don't reload messages if we're currently sending a message to this thread (to preserve optimistic updates)
2937 if (sendingToThreadIdRef.current !== threadId) {
30- loadMessages(threadId);
38+ loadMessages(threadId, onError);
3139 }
3240 } else {
3341 setMessages([]);
3442 setIsLoadingMessages(false);
3543 }
36- }, [threadId, loadMessages]);
44+ }, [threadId, loadMessages, onError]);
3745
3846 const sendMessage = async (
3947 message: string,
@@ -47,26 +55,30 @@ export function useMessages(threadId: number | null) {
4755 onThreadSelect: (id: number) => void,
4856 onThreadsReload: () => void,
4957 selectedModel: string = "gpt-oss",
50- maxPromptLength?: "none" | 1024 | 4096
58+ maxPromptLength?: "none" | 1024 | 4096,
59+ onError?: (error: string) => void
5160 ) => {
5261 if (!message.trim() || isLoading) return;
5362
5463 setIsLoading(true);
5564 let targetThreadId = currentThreadId;
5665
57- if (!targetThreadId) {
58- // Create a new thread if none exists
59- // Use the validated selectedModel instead of reading from localStorage
60- targetThreadId = await onCreateThread(
61- message.substring(0, 100),
62- message,
63- selectedModel,
64- maxPromptLength
65- );
6666 if (!targetThreadId) {
67- setIsLoading(false);
68- return;
69- }
67+ // Create a new thread if none exists
68+ // Use the validated selectedModel instead of reading from localStorage
69+ targetThreadId = await onCreateThread(
70+ message.substring(0, 100),
71+ message,
72+ selectedModel,
73+ maxPromptLength
74+ );
75+ if (!targetThreadId) {
76+ setIsLoading(false);
77+ if (onError) {
78+ onError("Failed to create thread");
79+ }
80+ return;
81+ }
7082 // Mark that we're sending to this thread before selecting it
7183 sendingToThreadIdRef.current = targetThreadId;
7284 onThreadSelect(targetThreadId);
@@ -80,6 +92,8 @@ export function useMessages(threadId: number | null) {
8092 role: "user",
8193 content: message,
8294 createdAt: new Date(),
95+ model: null,
96+ maxPromptLength: null,
8397 generationTimeMs: null,
8498 toolCalls: null,
8599 };
@@ -93,6 +107,8 @@ export function useMessages(threadId: number | null) {
93107 role: "assistant",
94108 content: "",
95109 createdAt: new Date(),
110+ model: null,
111+ maxPromptLength: null,
96112 generationTimeMs: null,
97113 toolCalls: null,
98114 };
@@ -111,7 +127,10 @@ export function useMessages(threadId: number | null) {
111127 });
112128
113129 if (!res.ok) {
114- throw new Error(`HTTP error! status: ${res.status}`);
130+ const errorData = await res.json().catch((parseError) => {
131+ throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
132+ });
133+ throw new Error(errorData.error || `HTTP error! status: ${res.status}`);
115134 }
116135
117136 if (!res.body) {
@@ -172,10 +191,14 @@ export function useMessages(threadId: number | null) {
172191 shouldStop = true;
173192 break;
174193 }
175- throw new Error(data.error || "Unknown error");
194+ const errorMsg = data.error || "Unknown error";
195+ if (onError) onError(errorMsg);
196+ throw new Error(errorMsg);
176197 }
177198 } catch (parseError) {
178- console.error("Failed to parse SSE data", parseError);
199+ if (onError && parseError instanceof Error) {
200+ onError(parseError.message);
201+ }
179202 }
180203 }
181204 }
@@ -187,9 +210,11 @@ export function useMessages(threadId: number | null) {
187210 } catch (error) {
188211 // Don't log abort errors as they're intentional
189212 if (error instanceof Error && error.name !== "AbortError") {
190- console.error("Failed to send message", error);
191213 // Only remove the assistant message on non-abort errors
192214 setMessages((prev) => prev.filter((msg) => msg.id !== assistantMsgId));
215+ if (onError && error instanceof Error) {
216+ onError(error.message);
217+ }
193218 }
194219 // For abort errors, keep the partial content
195220 setStreamingMessageId(null);
@@ -211,18 +236,27 @@ export function useMessages(threadId: number | null) {
211236 setMessages([]);
212237 };
213238
214- const deleteMessage = async (messageId: number, threadId: number) => {
239+ const deleteMessage = async (
240+ messageId: number,
241+ threadId: number,
242+ onError?: (error: string) => void
243+ ) => {
215244 try {
216245 const res = await fetch(`/api/threads/${threadId}/messages/${messageId}`, {
217246 method: "DELETE",
218247 });
219248 if (!res.ok) {
220- throw new Error("Failed to delete message");
249+ const errorData = await res.json().catch((parseError) => {
250+ throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
251+ });
252+ throw new Error(errorData.error || "Failed to delete message");
221253 }
222254 // Remove the message from local state
223255 setMessages((prev) => prev.filter((msg) => msg.id !== messageId));
224256 } catch (error) {
225- console.error("Failed to delete message", error);
257+ if (onError && error instanceof Error) {
258+ onError(error.message);
259+ }
226260 }
227261 };
228262
src/hooks/useModelSettings.ts+36−6
@@ -1,6 +1,6 @@
11 import { useState, useEffect } from "react";
22
3-export function useModelSettings() {
3+export function useModelSettings(onError?: (error: string) => void) {
44 const [selectedModel, setSelectedModel] = useState<string>("gpt-oss");
55 const [maxPromptLength, setMaxPromptLength] = useState<"none" | 1024 | 4096>("none");
66
@@ -10,6 +10,12 @@ export function useModelSettings() {
1010 try {
1111 // Load saved settings from API
1212 const settingsRes = await fetch("/api/settings");
13+ if (!settingsRes.ok) {
14+ const errorData = await settingsRes.json().catch((parseError) => {
15+ throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
16+ });
17+ throw new Error(errorData.error || settingsRes.statusText);
18+ }
1319 const settingsData = await settingsRes.json();
1420 const settings = settingsData.settings || {};
1521 const savedModel = settings.selectedModel || "gpt-oss";
@@ -17,6 +23,12 @@ export function useModelSettings() {
1723
1824 // Get available models
1925 const modelsRes = await fetch("/api/models");
26+ if (!modelsRes.ok) {
27+ const errorData = await modelsRes.json().catch((parseError) => {
28+ throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
29+ });
30+ throw new Error(errorData.error || modelsRes.statusText);
31+ }
2032 const modelsData = await modelsRes.json();
2133 const availableModels = modelsData.models || [];
2234
@@ -49,7 +61,9 @@ export function useModelSettings() {
4961 });
5062 }
5163 } catch (error) {
52- console.error("Failed to load/validate settings", error);
64+ if (onError && error instanceof Error) {
65+ onError(error.message);
66+ }
5367 // On error, keep defaults
5468 setSelectedModel("gpt-oss");
5569 setMaxPromptLength("none");
@@ -63,13 +77,21 @@ export function useModelSettings() {
6377 setSelectedModel(model);
6478 // Save to API
6579 try {
66- await fetch("/api/settings", {
80+ const res = await fetch("/api/settings", {
6781 method: "POST",
6882 headers: { "Content-Type": "application/json" },
6983 body: JSON.stringify({ selectedModel: model }),
7084 });
85+ if (!res.ok) {
86+ const errorData = await res.json().catch((parseError) => {
87+ throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
88+ });
89+ throw new Error(errorData.error || res.statusText);
90+ }
7191 } catch (error) {
72- console.error("Failed to save model", error);
92+ if (onError && error instanceof Error) {
93+ onError(error.message);
94+ }
7395 }
7496 };
7597
@@ -77,13 +99,21 @@ export function useModelSettings() {
7799 setMaxPromptLength(value);
78100 // Save to API
79101 try {
80- await fetch("/api/settings", {
102+ const res = await fetch("/api/settings", {
81103 method: "POST",
82104 headers: { "Content-Type": "application/json" },
83105 body: JSON.stringify({ maxPromptLength: value }),
84106 });
107+ if (!res.ok) {
108+ const errorData = await res.json().catch((parseError) => {
109+ throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
110+ });
111+ throw new Error(errorData.error || res.statusText);
112+ }
85113 } catch (error) {
86- console.error("Failed to save settings", error);
114+ if (onError && error instanceof Error) {
115+ onError(error.message);
116+ }
87117 }
88118 };
89119
src/hooks/useThreads.ts+46−17
@@ -6,23 +6,31 @@ export function useThreads() {
66 const [totalThreadCount, setTotalThreadCount] = useState<number>(0);
77 const [hasMoreThreads, setHasMoreThreads] = useState<boolean>(true);
88
9- const loadThreads = async (limit: number = 8) => {
9+ const loadThreads = async (limit: number = 8, onError?: (error: string) => void) => {
1010 try {
1111 const res = await fetch(`/api/threads?limit=${limit}`);
12+ if (!res.ok) {
13+ throw new Error(`Failed to load threads: ${res.status}`);
14+ }
1215 const data = await res.json();
1316 const threadsList = data.threads || [];
1417 setThreads(threadsList);
1518 setHasMoreThreads(data.hasMore || false);
1619 setTotalThreadCount(data.totalCount || 0);
17- } catch (error) {
18- console.error("Failed to load threads", error);
19- }
20+ } catch (error) {
21+ if (onError && error instanceof Error) {
22+ onError(error.message);
23+ }
24+ }
2025 };
2126
22- const loadMoreThreads = async (limit: number = 8) => {
27+ const loadMoreThreads = async (limit: number = 8, onError?: (error: string) => void) => {
2328 try {
2429 const offset = threads.length;
2530 const res = await fetch(`/api/threads?offset=${offset}&limit=${limit}`);
31+ if (!res.ok) {
32+ throw new Error(`Failed to load more threads: ${res.status}`);
33+ }
2634 const data = await res.json();
2735 const newThreads = data.threads || [];
2836 if (newThreads.length > 0) {
@@ -31,16 +39,19 @@ export function useThreads() {
3139 } else {
3240 setHasMoreThreads(false);
3341 }
34- } catch (error) {
35- console.error("Failed to load more threads", error);
36- }
42+ } catch (error) {
43+ if (onError && error instanceof Error) {
44+ onError(error.message);
45+ }
46+ }
3747 };
3848
3949 const createThread = async (
4050 titleOverride?: string,
4151 firstMessage?: string,
4252 model?: string,
43- maxPromptLength?: "none" | 1024 | 4096
53+ maxPromptLength?: "none" | 1024 | 4096,
54+ onError?: (error: string) => void
4455 ): Promise<number | null> => {
4556 try {
4657 const title = titleOverride || (firstMessage ? firstMessage.substring(0, 100) : "New Thread");
@@ -57,7 +68,6 @@ export function useThreads() {
5768 const settingsData = await settingsRes.json();
5869 maxPromptLengthToUse = settingsData.settings?.maxPromptLength || "none";
5970 } catch (error) {
60- console.error("Failed to load settings", error);
6171 maxPromptLengthToUse = "none";
6272 }
6373 }
@@ -71,6 +81,9 @@ export function useThreads() {
7181 maxPromptLength: maxPromptLengthToUse,
7282 }),
7383 });
84+ if (!res.ok) {
85+ throw new Error(`Failed to create thread: ${res.status}`);
86+ }
7487 const data = await res.json();
7588 const newThread = data.thread;
7689
@@ -79,14 +92,17 @@ export function useThreads() {
7992
8093 return newThread.id;
8194 } catch (error) {
82- console.error("Failed to create thread", error);
95+ if (onError && error instanceof Error) {
96+ onError(error.message);
97+ }
8398 return null;
8499 }
85100 };
86101
87102 const updateThread = async (
88103 threadId: number,
89- updates: { model?: string; maxPromptLength?: "none" | 1024 | 4096 | null }
104+ updates: { model?: string; maxPromptLength?: "none" | 1024 | 4096 | null },
105+ onError?: (error: string) => void
90106 ): Promise<void> => {
91107 try {
92108 const res = await fetch(`/api/threads/${threadId}`, {
@@ -95,7 +111,10 @@ export function useThreads() {
95111 body: JSON.stringify(updates),
96112 });
97113 if (!res.ok) {
98- throw new Error("Failed to update thread");
114+ const errorData = await res.json().catch((parseError) => {
115+ throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
116+ });
117+ throw new Error(errorData.error || "Failed to update thread");
99118 }
100119 const data = await res.json();
101120 const updatedThread = data.thread;
@@ -103,24 +122,34 @@ export function useThreads() {
103122 // Update the thread in local state
104123 setThreads((prev) => prev.map((t) => (t.id === threadId ? updatedThread : t)));
105124 } catch (error) {
106- console.error("Failed to update thread", error);
125+ const errorMsg =
126+ error instanceof Error ? error.message : "Failed to update thread";
127+ if (onError) onError(errorMsg);
107128 throw error;
108129 }
109130 };
110131
111- const deleteThread = async (threadId: number): Promise<void> => {
132+ const deleteThread = async (
133+ threadId: number,
134+ onError?: (error: string) => void
135+ ): Promise<void> => {
112136 try {
113137 const res = await fetch(`/api/threads/${threadId}`, {
114138 method: "DELETE",
115139 });
116140 if (!res.ok) {
117- throw new Error("Failed to delete thread");
141+ const errorData = await res.json().catch((parseError) => {
142+ throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
143+ });
144+ throw new Error(errorData.error || "Failed to delete thread");
118145 }
119146 // Remove the thread from the local state
120147 setThreads((prev) => prev.filter((t) => t.id !== threadId));
121148 setTotalThreadCount((prev) => Math.max(0, prev - 1));
122149 } catch (error) {
123- console.error("Failed to delete thread", error);
150+ const errorMsg =
151+ error instanceof Error ? error.message : "Failed to delete thread";
152+ if (onError) onError(errorMsg);
124153 throw error;
125154 }
126155 };
src/lib/ollama/duckduckgo.ts+0−1
@@ -117,7 +117,6 @@ export async function queryDuckDuckGo(query: string): Promise<string> {
117117 await setCache(cacheKey, result, CACHE_TTL_MS);
118118 return result;
119119 } catch (error) {
120- console.error("DuckDuckGo query error:", error);
121120 // Don't cache errors
122121 return `Error querying DuckDuckGo: ${error instanceof Error ? error.message : "Unknown error"}`;
123122 }
src/lib/ollama/weather.ts+0−1
@@ -183,7 +183,6 @@ export async function queryWeather(location: string): Promise<string> {
183183 await setCache(cacheKey, result, CACHE_TTL_MS);
184184 return result;
185185 } catch (error) {
186- console.error("Weather query error:", error);
187186 // Don't cache errors
188187 return `Error querying weather: ${error instanceof Error ? error.message : "Unknown error"}`;
189188 }
src/lib/ollama/websearch.ts+0−1
@@ -96,7 +96,6 @@ export async function queryWebSearch(query: string): Promise<string> {
9696 await setCache(cacheKey, result, CACHE_TTL_MS);
9797 return result;
9898 } catch (error) {
99- console.error("Web search error:", error);
10099 // Don't cache errors
101100 return `Error performing web search: ${error instanceof Error ? error.message : "Unknown error"}`;
102101 }