xonecas.io
53129
Pa

PAT / commit dc7a429

refactor: consolidate error handling and improve code modularity

- Create centralized error handling utilities (src/lib/errors.ts)
  - getErrorMessage() for consistent error message extraction
  - handleError() for unified error callback handling
  - getParseErrorMessage() for fetch error parsing

- Extract model fetching logic into reusable hook (src/hooks/useModels.ts)
  - Eliminates duplicate model fetching code
  - Provides isValidModel() validation helper

- Refactor useMessages hook to improve modularity
  - Extract helper functions: createUserMessage(), createAssistantMessage(),
    updateAssistantMessage(), handleTitleGeneration()
  - Break down large sendMessage function for better maintainability

- Simplify title generation cleanup logic
  - Consolidate repetitive regex replacements into cleaner pattern

- Simplify tool-runner execution logic
  - Remove unnecessary tool mapping object, use direct conditionals

- Update all components and hooks to use centralized error utilities
  - Consistent error handling across codebase
  - Reduced code duplication

All tests passing, linting and type checking verified.

xonecas2025-12-19 dc7a4299480f6226d4addb089a5df7379ec26600 parent 37ff2d6

10 files changed

app/page.tsx+16−47
@@ -9,12 +9,15 @@ import { useThreads } from "@/src/hooks/useThreads";
99 import { useMessages } from "@/src/hooks/useMessages";
1010 import { useThreadSelection } from "@/src/hooks/useThreadSelection";
1111 import { useLocalStorage } from "@/src/hooks/useLocalStorage";
12+import { useModels, isValidModel } from "@/src/hooks/useModels";
13+import { getErrorMessage } from "@/src/lib/errors";
1214 import "./highlight-theme.css";
1315
1416 export default function Home() {
1517 const [error, setError] = useState<string | null>(null);
1618 const { themeMode, handleThemeChange } = useTheme();
1719 const [selectedModel, setSelectedModel] = useLocalStorage<string>("selectedModel", "gpt-oss");
20+ const { models } = useModels();
1821 const [maxPromptLength, setMaxPromptLength] = useLocalStorage<"none" | 1024 | 4096>(
1922 "maxPromptLength",
2023 "none"
@@ -52,46 +55,18 @@ export default function Home() {
5255
5356 // Validate and initialize model from localStorage or fetch first available model
5457 useEffect(() => {
55- const initializeModel = async () => {
56- // Capture the current selectedModel value
57- const currentModel = selectedModel;
58- // Validate that the saved model still exists
59- if (currentModel) {
60- try {
61- const res = await fetch("/api/models");
62- if (res.ok) {
63- const data = await res.json();
64- const availableModels = data.models || [];
65- const modelExists = availableModels.some(
66- (m: { name: string; model: string }) => m.model === currentModel
67- );
68- if (modelExists) {
69- return;
70- }
71- }
72- } catch {
73- // Fall through to default
74- }
75- }
58+ if (models.length === 0) return;
7659
77- // If no saved model or it doesn't exist, get first available
78- try {
79- const res = await fetch("/api/models");
80- if (res.ok) {
81- const data = await res.json();
82- const availableModels = data.models || [];
83- if (availableModels.length > 0) {
84- const firstModel = availableModels[0].model;
85- setSelectedModel(firstModel);
86- }
87- }
88- } catch {
89- // Keep default
90- }
91- };
60+ // Validate that the saved model still exists
61+ if (selectedModel && isValidModel(selectedModel, models)) {
62+ return;
63+ }
9264
93- initializeModel();
94- }, [selectedModel, setSelectedModel]);
65+ // If no saved model or it doesn't exist, get first available
66+ if (models.length > 0) {
67+ setSelectedModel(models[0].model);
68+ }
69+ }, [models, selectedModel, setSelectedModel]);
9570
9671 const handleModelChange = (model: string) => {
9772 setSelectedModel(model);
@@ -148,9 +123,7 @@ export default function Home() {
148123 // Reload threads to ensure UI is in sync
149124 await loadThreads(8, setError);
150125 } catch (error) {
151- if (error instanceof Error) {
152- setError(error.message);
153- }
126+ setError(getErrorMessage(error));
154127 }
155128 };
156129
@@ -164,9 +137,7 @@ export default function Home() {
164137 clearMessages();
165138 }
166139 } catch (error) {
167- if (error instanceof Error) {
168- setError(error.message);
169- }
140+ setError(getErrorMessage(error));
170141 }
171142 };
172143
@@ -190,9 +161,7 @@ export default function Home() {
190161 setError
191162 );
192163 } catch (error) {
193- if (error instanceof Error) {
194- setError(error.message);
195- }
164+ setError(getErrorMessage(error));
196165 }
197166 };
198167
src/components/DeleteThreadButton.tsx+2−3
@@ -3,6 +3,7 @@
33 import { useState } from "react";
44 import TrashIcon from "@/src/components/icons/TrashIcon";
55 import DeleteConfirmationModal from "@/src/components/DeleteConfirmationModal";
6+import { handleError } from "@/src/lib/errors";
67
78 type DeleteThreadButtonProps = {
89 threadId: number;
@@ -26,9 +27,7 @@ export default function DeleteThreadButton({
2627 await onDeleteThread(threadId);
2728 setIsModalOpen(false);
2829 } catch (error) {
29- if (onError && error instanceof Error) {
30- onError(error.message);
31- }
30+ handleError(error, onError);
3231 } finally {
3332 setIsDeleting(false);
3433 }
src/components/ThreadSettingsModal.tsx+5−38
@@ -5,6 +5,8 @@ import Modal from "@/src/components/Modal";
55 import SecondaryButton from "@/src/components/buttons/SecondaryButton";
66 import TrashIcon from "@/src/components/icons/TrashIcon";
77 import type { Thread } from "@/src/lib/db/schema";
8+import { useModels } from "@/src/hooks/useModels";
9+import { handleError } from "@/src/lib/errors";
810
911 type ThreadSettingsModalProps = {
1012 isOpen: boolean;
@@ -42,8 +44,7 @@ export default function ThreadSettingsModal({
4244 onMaxPromptLengthChange,
4345 onUserPromptChange,
4446 }: ThreadSettingsModalProps) {
45- const [models, setModels] = useState<Array<{ name: string; model: string }>>([]);
46- const [isLoadingModels, setIsLoadingModels] = useState(false);
47+ const { models, isLoading: isLoadingModels } = useModels(onError);
4748 const [selectedModel, setSelectedModel] = useState<string>("gpt-oss");
4849 const [maxPromptLength, setMaxPromptLength] = useState<"none" | 1024 | 4096 | null>("none");
4950 const [userPrompt, setUserPrompt] = useState<string>("");
@@ -51,36 +52,6 @@ export default function ThreadSettingsModal({
5152 const [isDeleting, setIsDeleting] = useState(false);
5253 const isNewThread = thread === null;
5354
54- // Load models when modal opens
55- useEffect(() => {
56- if (isOpen) {
57- setIsLoadingModels(true);
58- fetch("/api/models")
59- .then(async (res) => {
60- if (!res.ok) {
61- const errorData = await res.json().catch((parseError) => {
62- throw new Error(
63- `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
64- );
65- });
66- throw new Error(errorData.error || res.statusText);
67- }
68- return res.json();
69- })
70- .then((data) => {
71- const availableModels = data.models || [];
72- setModels(availableModels);
73- setIsLoadingModels(false);
74- })
75- .catch((error) => {
76- setIsLoadingModels(false);
77- if (onError && error instanceof Error) {
78- onError(error.message);
79- }
80- });
81- }
82- }, [isOpen, onError]);
83-
8455 // Load thread settings when thread changes or when modal opens for new thread
8556 useEffect(() => {
8657 if (thread) {
@@ -135,9 +106,7 @@ export default function ThreadSettingsModal({
135106 });
136107 onClose();
137108 } catch (error) {
138- if (onError && error instanceof Error) {
139- onError(error.message);
140- }
109+ handleError(error, onError);
141110 } finally {
142111 setIsSaving(false);
143112 }
@@ -151,9 +120,7 @@ export default function ThreadSettingsModal({
151120 await onDeleteThread(thread.id);
152121 onClose();
153122 } catch (error) {
154- if (onError && error instanceof Error) {
155- onError(error.message);
156- }
123+ handleError(error, onError);
157124 } finally {
158125 setIsDeleting(false);
159126 }
src/hooks/useMessages.ts+100−108
@@ -1,5 +1,6 @@
11 import { useState, useEffect, useCallback, useRef } from "react";
22 import type { Message } from "@/src/lib/db/schema";
3+import { getParseErrorMessage, handleError } from "@/src/lib/errors";
34
45 /**
56 * Custom hook for managing messages within a thread.
@@ -41,14 +42,91 @@ export function useMessages(
4142 const loadedMessages = data.messages || [];
4243 setMessages(loadedMessages);
4344 } catch (error) {
44- if (onError && error instanceof Error) {
45- onError(error.message);
46- }
45+ handleError(error, onError);
4746 } finally {
4847 setIsLoadingMessages(false);
4948 }
5049 }, []);
5150
51+ const createUserMessage = (message: string, threadId: number): Message => ({
52+ id: Date.now(),
53+ threadId,
54+ role: "user",
55+ content: message,
56+ createdAt: new Date(),
57+ model: null,
58+ maxPromptLength: null,
59+ generationTimeMs: null,
60+ toolCallCounts: null,
61+ });
62+
63+ const createAssistantMessage = (
64+ id: number,
65+ threadId: number,
66+ content: string,
67+ metadata?: {
68+ model?: string | null;
69+ maxPromptLength?: number | null;
70+ toolCallCounts?: string | null;
71+ }
72+ ): Message => ({
73+ id,
74+ threadId,
75+ role: "assistant",
76+ content,
77+ createdAt: new Date(),
78+ model: metadata?.model ?? null,
79+ maxPromptLength: metadata?.maxPromptLength ?? null,
80+ generationTimeMs: null,
81+ toolCallCounts: metadata?.toolCallCounts ?? null,
82+ });
83+
84+ const updateAssistantMessage = (
85+ messageId: number,
86+ content: string,
87+ metadata?: {
88+ model?: string | null;
89+ maxPromptLength?: number | null;
90+ toolCallCounts?: string | null;
91+ }
92+ ) => {
93+ setMessages((prev) =>
94+ prev.map((msg) =>
95+ msg.id === messageId
96+ ? {
97+ ...msg,
98+ content,
99+ model: metadata?.model ?? msg.model,
100+ maxPromptLength: metadata?.maxPromptLength ?? msg.maxPromptLength,
101+ toolCallCounts: metadata?.toolCallCounts ?? msg.toolCallCounts,
102+ }
103+ : msg
104+ )
105+ );
106+ };
107+
108+ const handleTitleGeneration = async (
109+ threadId: number,
110+ threadModel: string,
111+ onUpdateThreadTitle?: (threadId: number, title: string) => Promise<void>
112+ ) => {
113+ if (!onUpdateThreadTitle) return;
114+
115+ try {
116+ const titleRes = await fetch(`/api/threads/${threadId}/title`, {
117+ method: "POST",
118+ });
119+ if (titleRes.ok) {
120+ const titleData = await titleRes.json();
121+ if (titleData.title) {
122+ await onUpdateThreadTitle(threadId, titleData.title);
123+ }
124+ }
125+ } catch {
126+ // Silently fail title generation - don't interrupt the flow
127+ }
128+ };
129+
52130 useEffect(() => {
53131 if (threadId !== null) {
54132 // Don't reload messages if we're currently sending a message to this thread (to preserve optimistic updates)
@@ -92,17 +170,7 @@ export function useMessages(
92170 sendingToThreadIdRef.current = targetThreadId;
93171 }
94172
95- const userMsg: Message = {
96- id: Date.now(),
97- threadId: targetThreadId,
98- role: "user",
99- content: message,
100- createdAt: new Date(),
101- model: null,
102- maxPromptLength: null,
103- generationTimeMs: null,
104- toolCallCounts: null,
105- };
173+ const userMsg = createUserMessage(message, targetThreadId);
106174 setMessages((prev) => [...prev, userMsg]);
107175
108176 // Create assistant message placeholder (but don't add it yet - wait for content)
@@ -122,9 +190,7 @@ export function useMessages(
122190
123191 if (!res.ok) {
124192 const errorData = await res.json().catch((parseError) => {
125- throw new Error(
126- `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
127- );
193+ throw new Error(getParseErrorMessage(parseError));
128194 });
129195 throw new Error(errorData.error || `HTTP error! status: ${res.status}`);
130196 }
@@ -157,68 +223,30 @@ export function useMessages(
157223 accumulatedContent += data.content || "";
158224 // Only add the message when we have content
159225 if (!messageAdded && accumulatedContent.trim()) {
160- const botMsg: Message = {
161- id: assistantMsgId,
162- threadId: targetThreadId,
163- role: "assistant",
164- content: accumulatedContent,
165- createdAt: new Date(),
166- model: null,
167- maxPromptLength: null,
168- generationTimeMs: null,
169- toolCallCounts: null,
170- };
226+ const botMsg = createAssistantMessage(assistantMsgId, targetThreadId, accumulatedContent);
171227 setMessages((prev) => [...prev, botMsg]);
172228 messageAdded = true;
173229 } else if (messageAdded) {
174- setMessages((prev) =>
175- prev.map((msg) =>
176- msg.id === assistantMsgId ? { ...msg, content: accumulatedContent } : msg
177- )
178- );
230+ updateAssistantMessage(assistantMsgId, accumulatedContent);
179231 }
180232 } else if (data.type === "done") {
181233 // Final update with complete answer and metadata
182- // If message wasn't added yet (no content received), add it now
234+ const finalContent = data.answer || accumulatedContent;
235+ const metadata = {
236+ model: data.model || null,
237+ maxPromptLength: data.maxPromptLength !== undefined ? data.maxPromptLength : null,
238+ toolCallCounts: data.toolCallCounts !== undefined ? data.toolCallCounts : null,
239+ };
240+
183241 if (!messageAdded) {
184- const botMsg: Message = {
185- id: assistantMsgId,
186- threadId: targetThreadId,
187- role: "assistant",
188- content: data.answer || accumulatedContent,
189- createdAt: new Date(),
190- model: data.model || null,
191- maxPromptLength:
192- data.maxPromptLength !== undefined ? data.maxPromptLength : null,
193- generationTimeMs: null,
194- toolCallCounts: data.toolCallCounts !== undefined ? data.toolCallCounts : null,
195- };
242+ const botMsg = createAssistantMessage(assistantMsgId, targetThreadId, finalContent, metadata);
196243 setMessages((prev) => [...prev, botMsg]);
197244 } else {
198- setMessages((prev) =>
199- prev.map((msg) =>
200- msg.id === assistantMsgId
201- ? {
202- ...msg,
203- content: data.answer || accumulatedContent,
204- model: data.model || msg.model,
205- maxPromptLength:
206- data.maxPromptLength !== undefined
207- ? data.maxPromptLength
208- : msg.maxPromptLength,
209- toolCallCounts:
210- data.toolCallCounts !== undefined
211- ? data.toolCallCounts
212- : msg.toolCallCounts,
213- }
214- : msg
215- )
216- );
245+ updateAssistantMessage(assistantMsgId, finalContent, metadata);
217246 }
218247 setStreamingMessageId(null);
219248
220249 // Generate title after first assistant response
221- // Check if this is the first response (exactly 1 user message and 1 assistant message, excluding system messages)
222250 const previousUserMessages = messages.filter(
223251 (m) => m.role === "user" && m.threadId === targetThreadId
224252 );
@@ -226,7 +254,6 @@ export function useMessages(
226254 (m) => m.role === "assistant" && m.threadId === targetThreadId
227255 );
228256
229- // After this response, we'll have: previous user messages + this user message, and previous assistant messages + this assistant message
230257 const totalUserMessages = previousUserMessages.length + 1;
231258 const totalAssistantMessages = previousAssistantMessages.length + 1;
232259
@@ -236,24 +263,7 @@ export function useMessages(
236263 onUpdateThreadTitle &&
237264 data.model
238265 ) {
239- // This is the first response, generate a title
240- const threadModel = data.model;
241-
242- if (threadModel) {
243- try {
244- const titleRes = await fetch(`/api/threads/${targetThreadId}/title`, {
245- method: "POST",
246- });
247- if (titleRes.ok) {
248- const titleData = await titleRes.json();
249- if (titleData.title) {
250- await onUpdateThreadTitle(targetThreadId, titleData.title);
251- }
252- }
253- } catch {
254- // Silently fail title generation - don't interrupt the flow
255- }
256- }
266+ await handleTitleGeneration(targetThreadId, data.model, onUpdateThreadTitle);
257267 }
258268
259269 shouldStop = true;
@@ -264,17 +274,7 @@ export function useMessages(
264274 if (data.error === "Generation stopped") {
265275 // If we have content but message wasn't added, add it now
266276 if (!messageAdded && accumulatedContent.trim()) {
267- const botMsg: Message = {
268- id: assistantMsgId,
269- threadId: targetThreadId,
270- role: "assistant",
271- content: accumulatedContent,
272- createdAt: new Date(),
273- model: null,
274- maxPromptLength: null,
275- generationTimeMs: null,
276- toolCallCounts: null,
277- };
277+ const botMsg = createAssistantMessage(assistantMsgId, targetThreadId, accumulatedContent);
278278 setMessages((prev) => [...prev, botMsg]);
279279 }
280280 setStreamingMessageId(null);
@@ -286,9 +286,7 @@ export function useMessages(
286286 throw new Error(errorMsg);
287287 }
288288 } catch (parseError) {
289- if (onError && parseError instanceof Error) {
290- onError(parseError.message);
291- }
289+ handleError(parseError, onError);
292290 }
293291 }
294292 }
@@ -302,9 +300,7 @@ export function useMessages(
302300 if (error instanceof Error && error.name !== "AbortError") {
303301 // Only remove the assistant message on non-abort errors (if it was added)
304302 setMessages((prev) => prev.filter((msg) => msg.id !== assistantMsgId));
305- if (onError && error instanceof Error) {
306- onError(error.message);
307- }
303+ handleError(error, onError);
308304 }
309305 // For abort errors, keep the partial content (message will be added if it has content)
310306 setStreamingMessageId(null);
@@ -337,18 +333,14 @@ export function useMessages(
337333 });
338334 if (!res.ok) {
339335 const errorData = await res.json().catch((parseError) => {
340- throw new Error(
341- `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
342- );
336+ throw new Error(getParseErrorMessage(parseError));
343337 });
344338 throw new Error(errorData.error || "Failed to delete message");
345339 }
346340 // Remove the message from local state
347341 setMessages((prev) => prev.filter((msg) => msg.id !== messageId));
348342 } catch (error) {
349- if (onError && error instanceof Error) {
350- onError(error.message);
351- }
343+ handleError(error, onError);
352344 }
353345 };
354346
src/hooks/useModels.ts+58−0
@@ -0,0 +1,58 @@
1+import { useState, useEffect } from "react";
2+import { handleError } from "@/src/lib/errors";
3+
4+export type Model = {
5+ name: string;
6+ model: string;
7+};
8+
9+/**
10+ * Custom hook for fetching and managing available Ollama models.
11+ * @param onError - Optional error callback function
12+ * @returns Object containing models array and loading state
13+ */
14+export function useModels(onError?: (error: string) => void) {
15+ const [models, setModels] = useState<Model[]>([]);
16+ const [isLoading, setIsLoading] = useState(true);
17+
18+ useEffect(() => {
19+ let cancelled = false;
20+
21+ fetch("/api/models")
22+ .then(async (res) => {
23+ if (!res.ok) {
24+ throw new Error(`Failed to fetch models: ${res.status}`);
25+ }
26+ return res.json();
27+ })
28+ .then((data) => {
29+ if (!cancelled) {
30+ setModels(data.models || []);
31+ setIsLoading(false);
32+ }
33+ })
34+ .catch((error) => {
35+ if (!cancelled) {
36+ setIsLoading(false);
37+ handleError(error, onError);
38+ }
39+ });
40+
41+ return () => {
42+ cancelled = true;
43+ };
44+ }, [onError]);
45+
46+ return { models, isLoading };
47+}
48+
49+/**
50+ * Validates if a model exists in the available models list.
51+ * @param modelName - The model name to validate
52+ * @param models - Array of available models
53+ * @returns True if the model exists
54+ */
55+export function isValidModel(modelName: string, models: Model[]): boolean {
56+ return models.some((m) => m.model === modelName);
57+}
58+
src/hooks/useThreads.ts+10−19
@@ -1,5 +1,6 @@
11 import { useState, useEffect } from "react";
22 import type { Thread } from "@/src/lib/db/schema";
3+import { getErrorMessage, getParseErrorMessage, handleError } from "@/src/lib/errors";
34
45 /**
56 * Custom hook for managing conversation threads.
@@ -32,9 +33,7 @@ export function useThreads() {
3233 setHasMoreThreads(data.hasMore || false);
3334 setTotalThreadCount(data.totalCount || 0);
3435 } catch (error) {
35- if (onError && error instanceof Error) {
36- onError(error.message);
37- }
36+ handleError(error, onError);
3837 }
3938 };
4039
@@ -54,9 +53,7 @@ export function useThreads() {
5453 setHasMoreThreads(false);
5554 }
5655 } catch (error) {
57- if (onError && error instanceof Error) {
58- onError(error.message);
59- }
56+ handleError(error, onError);
6057 }
6158 };
6259
@@ -92,9 +89,7 @@ export function useThreads() {
9289
9390 return newThread.id;
9491 } catch (error) {
95- if (onError && error instanceof Error) {
96- onError(error.message);
97- }
92+ handleError(error, onError);
9893 return null;
9994 }
10095 };
@@ -121,9 +116,7 @@ export function useThreads() {
121116 });
122117 if (!res.ok) {
123118 const errorData = await res.json().catch((parseError) => {
124- throw new Error(
125- `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
126- );
119+ throw new Error(getParseErrorMessage(parseError));
127120 });
128121 throw new Error(errorData.error || "Failed to update thread");
129122 }
@@ -133,8 +126,8 @@ export function useThreads() {
133126 // Update the thread in local state
134127 setThreads((prev) => prev.map((t) => (t.id === threadId ? updatedThread : t)));
135128 } catch (error) {
136- const errorMsg = error instanceof Error ? error.message : "Failed to update thread";
137- if (onError) onError(errorMsg);
129+ const errorMsg = getErrorMessage(error, "Failed to update thread");
130+ handleError(errorMsg, onError);
138131 throw error;
139132 }
140133 };
@@ -149,9 +142,7 @@ export function useThreads() {
149142 });
150143 if (!res.ok) {
151144 const errorData = await res.json().catch((parseError) => {
152- throw new Error(
153- `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
154- );
145+ throw new Error(getParseErrorMessage(parseError));
155146 });
156147 throw new Error(errorData.error || "Failed to delete thread");
157148 }
@@ -159,8 +150,8 @@ export function useThreads() {
159150 setThreads((prev) => prev.filter((t) => t.id !== threadId));
160151 setTotalThreadCount((prev) => Math.max(0, prev - 1));
161152 } catch (error) {
162- const errorMsg = error instanceof Error ? error.message : "Failed to delete thread";
163- if (onError) onError(errorMsg);
153+ const errorMsg = getErrorMessage(error, "Failed to delete thread");
154+ handleError(errorMsg, onError);
164155 throw error;
165156 }
166157 };
src/lib/errors.ts+33−0
@@ -0,0 +1,33 @@
1+/* personal-assistant-thing/src/lib/errors.ts */
2+// Centralized error handling utilities
3+
4+/**
5+ * Extracts an error message from an error object.
6+ * @param error - The error to extract a message from
7+ * @param defaultMessage - Default message if error is not an Error instance
8+ * @returns The error message
9+ */
10+export function getErrorMessage(error: unknown, defaultMessage = "Unknown error"): string {
11+ return error instanceof Error ? error.message : defaultMessage;
12+}
13+
14+/**
15+ * Handles an error by calling the error callback if provided.
16+ * @param error - The error to handle
17+ * @param onError - Optional error callback function
18+ */
19+export function handleError(error: unknown, onError?: (error: string) => void): void {
20+ if (onError) {
21+ onError(getErrorMessage(error));
22+ }
23+}
24+
25+/**
26+ * Parses an error response from a fetch request.
27+ * @param parseError - The error that occurred during parsing
28+ * @returns A formatted error message
29+ */
30+export function getParseErrorMessage(parseError: unknown): string {
31+ return `Failed to parse error response: ${getErrorMessage(parseError, "Invalid JSON")}`;
32+}
33+
src/lib/ollama/chat/ollama-chat.ts+2−1
@@ -2,6 +2,7 @@
22
33 import ollama, { type Message, type ToolCall } from "ollama";
44 import { debug } from "@/src/lib/debug";
5+import { getErrorMessage } from "@/src/lib/errors";
56 import { duckDuckGoTool } from "@/src/lib/ollama/tools/duckduckgo";
67 import { fetchPageTool } from "@/src/lib/ollama/tools/fetchpage";
78 import { weatherTool } from "@/src/lib/ollama/tools/weather";
@@ -181,7 +182,7 @@ export async function OllamaChat(
181182 const toolResponse = await executeToolCall(toolCall);
182183 currentMessages.push(toolResponse);
183184 } catch (error) {
184- const errorMessage = error instanceof Error ? error.message : "Unknown error";
185+ const errorMessage = getErrorMessage(error);
185186 debug(`[Ollama] Tool execution failed: ${errorMessage}`);
186187 // Add error message as tool response so the model can handle it
187188 currentMessages.push({
src/lib/ollama/title.ts+5−6
@@ -3,6 +3,7 @@
33
44 import ollama from "ollama";
55 import { debug } from "@/src/lib/debug";
6+import { getErrorMessage } from "@/src/lib/errors";
67
78 /**
89 * Generates a concise title for a conversation based on message contents.
@@ -53,11 +54,9 @@ export async function generateTitle(
5354 // Clean up markdown characters and quotes
5455 const generatedTitle = response.response
5556 .trim()
56- .replace(/^["']|["']$/g, "")
57- .replace(/[*#`\[\](){}]/g, "")
58- .replace(/^#+\s*/, "")
59- .replace(/\*\*/g, "")
60- .replace(/\*/g, "")
57+ .replace(/^["']|["']$/g, "") // Remove surrounding quotes
58+ .replace(/^#+\s*/g, "") // Remove markdown headers
59+ .replace(/[*#`\[\](){}]/g, "") // Remove markdown formatting characters
6160 .trim();
6261
6362 if (!generatedTitle) {
@@ -67,7 +66,7 @@ export async function generateTitle(
6766
6867 return generatedTitle;
6968 } catch (err) {
70- debug(`[Title] Error:`, err instanceof Error ? err.message : "Unknown error");
69+ debug(`[Title] Error:`, getErrorMessage(err));
7170 return null;
7271 }
7372 }
src/lib/ollama/tools/tool-runner.ts+6−11
@@ -2,6 +2,7 @@
22
33 import { type Message, type ToolCall } from "ollama";
44 import { debug } from "@/src/lib/debug";
5+import { getErrorMessage } from "@/src/lib/errors";
56 import { queryDuckDuckGo, fetchPage, queryWeather, queryWebSearch } from "@/src/lib/ollama/tools";
67
78 /**
@@ -116,28 +117,22 @@ export async function executeToolCall(toolCall: ToolCall): Promise<Message> {
116117
117118 const { query, url, timezone, forecastDays } = validationResult;
118119
119- type ToolName = "query_web_search" | "query_weather" | "query_duckduckgo" | "fetch_page";
120- const tools: Record<ToolName, (query: string) => Promise<string>> = {
121- query_web_search: queryWebSearch,
122- query_weather: queryWeather,
123- query_duckduckgo: queryDuckDuckGo,
124- fetch_page: fetchPage,
125- };
126-
127120 let result: string;
128121 try {
129122 if (name === "query_weather") {
130123 result = await queryWeather(query!, timezone, forecastDays);
131124 } else if (name === "fetch_page") {
132125 result = await fetchPage(url!);
133- } else if (name in tools) {
134- result = await tools[name as ToolName](query!);
126+ } else if (name === "query_web_search") {
127+ result = await queryWebSearch(query!);
128+ } else if (name === "query_duckduckgo") {
129+ result = await queryDuckDuckGo(query!);
135130 } else {
136131 throw new Error(`Unknown tool: ${name}`);
137132 }
138133 debug(`[Tool] ${name} completed (${result.length} chars)`);
139134 } catch (error) {
140- const errorMessage = error instanceof Error ? error.message : "Unknown error";
135+ const errorMessage = getErrorMessage(error);
141136 debug(`[Tool] ${name} failed: ${errorMessage}`);
142137 result = `Error: ${errorMessage}`;
143138 }