@@ -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