xonecas.io
53129
Pa

PAT / commit efc9557

refactor: consolidate useThreadManagement into useThreads

xonecas2025-12-19 efc95575f6a75169ec7fc748064ab7f2c769b668 parent f6db8ff

3 files changed

app/page.tsx+21−17
@@ -1,5 +1,5 @@
11 "use client";
2-import { useRef, useMemo, useCallback } from "react";
2+import { useRef, useMemo, useCallback, 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";
@@ -11,7 +11,6 @@ import { useThreadSelection } from "@/src/hooks/useThreadSelection";
1111 import { useLocalStorage } from "@/src/hooks/useLocalStorage";
1212 import { useModelValidation } from "@/src/hooks/useModelValidation";
1313 import { useErrorWithAutoDismiss } from "@/src/hooks/useErrorWithAutoDismiss";
14-import { useThreadManagement } from "@/src/hooks/useThreadManagement";
1514 import { getErrorMessage } from "@/src/lib/errors";
1615 import "./highlight-theme.css";
1716
@@ -30,6 +29,11 @@ export default function Home() {
3029
3130 useModelValidation(selectedModel, setSelectedModel);
3231
32+ const { currentThreadId, selectThread, deselectThread, messagesContainerRef } =
33+ useThreadSelection();
34+
35+ const clearMessagesRef = useRef<(() => void) | undefined>(undefined);
36+
3337 const {
3438 threads,
3539 totalThreadCount,
@@ -38,10 +42,17 @@ export default function Home() {
3842 loadMoreThreads,
3943 createThread,
4044 updateThread,
41- deleteThread,
42- } = useThreads();
43- const { currentThreadId, selectThread, deselectThread, messagesContainerRef } =
44- useThreadSelection();
45+ handleThreadSelect,
46+ handleThreadUpdate,
47+ handleThreadDelete,
48+ } = useThreads({
49+ selectThread,
50+ deselectThread,
51+ clearMessagesRef,
52+ currentThreadId,
53+ setError,
54+ });
55+
4556 const {
4657 messages,
4758 isLoading,
@@ -55,18 +66,11 @@ export default function Home() {
5566 await updateThread(threadId, { title }, setError);
5667 await loadThreads(8, setError);
5768 });
58- const messageInputRef = useRef<MessageInputRef>(null);
5969
60- const { handleThreadSelect, handleThreadUpdate, handleThreadDelete } = useThreadManagement(
61- updateThread,
62- deleteThread,
63- loadThreads,
64- selectThread,
65- deselectThread,
66- clearMessages,
67- currentThreadId,
68- setError
69- );
70+ useEffect(() => {
71+ clearMessagesRef.current = clearMessages;
72+ }, [clearMessages]);
73+ const messageInputRef = useRef<MessageInputRef>(null);
7074
7175 const handleModelChange = useCallback(
7276 (model: string) => {
src/hooks/useThreadManagement.ts+0−81
@@ -1,81 +0,0 @@
1-import { useCallback } from "react";
2-import { getErrorMessage } from "@/src/lib/errors";
3-
4-type ThreadUpdates = {
5- model?: string;
6- maxPromptLength?: "none" | 1024 | 4096 | null;
7- userPrompt?: string | null;
8- title?: string;
9-};
10-
11-/**
12- * Custom hook for managing thread operations with error handling.
13- * Provides handlers for thread selection, creation, update, and deletion.
14- *
15- * @param updateThread - Function to update a thread
16- * @param deleteThread - Function to delete a thread
17- * @param loadThreads - Function to reload threads list
18- * @param selectThread - Function to select a thread
19- * @param deselectThread - Function to deselect current thread
20- * @param clearMessages - Function to clear messages
21- * @param currentThreadId - Currently selected thread ID
22- * @param setError - Function to set error state
23- * @returns Object containing thread management handlers
24- */
25-export function useThreadManagement(
26- updateThread: (
27- threadId: number,
28- updates: ThreadUpdates,
29- onError?: (error: string) => void
30- ) => Promise<void>,
31- deleteThread: (threadId: number, onError?: (error: string) => void) => Promise<void>,
32- loadThreads: (limit: number, onError?: (error: string) => void) => Promise<void>,
33- selectThread: (threadId: number) => void,
34- deselectThread: () => void,
35- clearMessages: () => void,
36- currentThreadId: number | null,
37- setError: (error: string | null) => void
38-) {
39- const handleThreadSelect = useCallback(
40- (threadId: number) => {
41- setError(null);
42- selectThread(threadId);
43- },
44- [selectThread, setError]
45- );
46-
47- const handleThreadUpdate = useCallback(
48- async (threadId: number, updates: ThreadUpdates) => {
49- setError(null);
50- try {
51- await updateThread(threadId, updates, setError);
52- await loadThreads(8, setError);
53- } catch (error) {
54- setError(getErrorMessage(error));
55- }
56- },
57- [updateThread, loadThreads, setError]
58- );
59-
60- const handleThreadDelete = useCallback(
61- async (threadId: number) => {
62- setError(null);
63- try {
64- await deleteThread(threadId, setError);
65- if (currentThreadId === threadId) {
66- deselectThread();
67- clearMessages();
68- }
69- } catch (error) {
70- setError(getErrorMessage(error));
71- }
72- },
73- [deleteThread, currentThreadId, deselectThread, clearMessages, setError]
74- );
75-
76- return {
77- handleThreadSelect,
78- handleThreadUpdate,
79- handleThreadDelete,
80- };
81-}
src/hooks/useThreads.ts+191−109
@@ -1,11 +1,29 @@
1-import { useState, useEffect } from "react";
1+import { useState, useEffect, useCallback, useRef } from "react";
2+import type React from "react";
23 import type { Thread } from "@/src/lib/db/schema";
3-import { getErrorMessage, getParseErrorMessage, handleError } from "@/src/lib/errors";
4+import { getErrorMessage, handleError } from "@/src/lib/errors";
5+import { useFetch } from "./useFetch";
6+
7+export type ThreadUpdates = {
8+ model?: string;
9+ maxPromptLength?: "none" | 1024 | 4096 | null;
10+ userPrompt?: string | null;
11+ title?: string;
12+};
13+
14+type ThreadManagementConfig = {
15+ selectThread: (threadId: number) => void;
16+ deselectThread: () => void;
17+ clearMessagesRef?: React.MutableRefObject<(() => void) | undefined>;
18+ currentThreadId: number | null;
19+ setError: (error: string | null) => void;
20+};
421
522 /**
623 * Custom hook for managing conversation threads.
724 * Provides state and functions for loading, creating, updating, and deleting threads.
825 *
26+ * @param config - Optional configuration for thread management handlers
927 * @returns Object containing:
1028 * - `threads` - Array of currently loaded threads
1129 * - `totalThreadCount` - Total number of threads in the database
@@ -15,60 +33,72 @@ import { getErrorMessage, getParseErrorMessage, handleError } from "@/src/lib/er
1533 * - `createThread` - Function to create a new thread
1634 * - `updateThread` - Function to update an existing thread
1735 * - `deleteThread` - Function to delete a thread
36+ * - `handleThreadSelect` - Handler for thread selection (only if config provided)
37+ * - `handleThreadUpdate` - Handler for thread updates (only if config provided)
38+ * - `handleThreadDelete` - Handler for thread deletion (only if config provided)
1839 */
19-export function useThreads() {
40+export function useThreads(config?: ThreadManagementConfig) {
2041 const [threads, setThreads] = useState<Thread[]>([]);
2142 const [totalThreadCount, setTotalThreadCount] = useState<number>(0);
2243 const [hasMoreThreads, setHasMoreThreads] = useState<boolean>(true);
44+ const fetchWithErrorHandling = useFetch();
45+ const hasLoadedRef = useRef(false);
2346
24- const loadThreads = async (limit: number = 8, onError?: (error: string) => void) => {
25- try {
26- const res = await fetch(`/api/threads?limit=${limit}`);
27- if (!res.ok) {
28- throw new Error(`Failed to load threads: ${res.status}`);
47+ const loadThreads = useCallback(
48+ async (limit: number = 8, onError?: (error: string) => void) => {
49+ const data = await fetchWithErrorHandling<{
50+ threads: Thread[];
51+ hasMore: boolean;
52+ totalCount: number;
53+ }>(`/api/threads?limit=${limit}`, { errorMessage: "Failed to load threads", onError });
54+ if (data) {
55+ const threadsList = data.threads || [];
56+ setThreads(threadsList);
57+ setHasMoreThreads(data.hasMore || false);
58+ setTotalThreadCount(data.totalCount || 0);
2959 }
30- const data = await res.json();
31- const threadsList = data.threads || [];
32- setThreads(threadsList);
33- setHasMoreThreads(data.hasMore || false);
34- setTotalThreadCount(data.totalCount || 0);
35- } catch (error) {
36- handleError(error, onError);
37- }
38- };
60+ },
61+ [fetchWithErrorHandling]
62+ );
3963
40- const loadMoreThreads = async (limit: number = 8, onError?: (error: string) => void) => {
41- try {
64+ const loadMoreThreads = useCallback(
65+ async (limit: number = 8, onError?: (error: string) => void) => {
4266 const offset = threads.length;
43- const res = await fetch(`/api/threads?offset=${offset}&limit=${limit}`);
44- if (!res.ok) {
45- throw new Error(`Failed to load more threads: ${res.status}`);
67+ const data = await fetchWithErrorHandling<{ threads: Thread[]; hasMore: boolean }>(
68+ `/api/threads?offset=${offset}&limit=${limit}`,
69+ { errorMessage: "Failed to load more threads", onError }
70+ );
71+ if (data) {
72+ const newThreads = data.threads || [];
73+ if (newThreads.length > 0) {
74+ setThreads((prev) => [...prev, ...newThreads]);
75+ setHasMoreThreads(data.hasMore || false);
76+ } else {
77+ setHasMoreThreads(false);
78+ }
4679 }
47- const data = await res.json();
48- const newThreads = data.threads || [];
49- if (newThreads.length > 0) {
50- setThreads((prev) => [...prev, ...newThreads]);
51- setHasMoreThreads(data.hasMore || false);
52- } else {
53- setHasMoreThreads(false);
54- }
55- } catch (error) {
56- handleError(error, onError);
57- }
58- };
80+ },
81+ [threads.length, fetchWithErrorHandling]
82+ );
5983
60- const createThread = async (
61- model: string,
62- maxPromptLength: "none" | 1024 | 4096,
63- titleOverride?: string,
64- firstMessage?: string,
65- userPrompt?: string,
66- onError?: (error: string) => void
67- ): Promise<{ threadId: number; systemMessage?: { id: number; content: string; createdAt: string } } | null> => {
68- try {
84+ const createThread = useCallback(
85+ async (
86+ model: string,
87+ maxPromptLength: "none" | 1024 | 4096,
88+ titleOverride?: string,
89+ firstMessage?: string,
90+ userPrompt?: string,
91+ onError?: (error: string) => void
92+ ): Promise<{
93+ threadId: number;
94+ systemMessage?: { id: number; content: string; createdAt: string };
95+ } | null> => {
6996 const title = titleOverride || (firstMessage ? firstMessage.substring(0, 100) : "New Thread");
7097
71- const res = await fetch("/api/threads", {
98+ const data = await fetchWithErrorHandling<{
99+ thread: Thread;
100+ systemMessage?: { id: number; content: string; createdAt: string };
101+ }>("/api/threads", {
72102 method: "POST",
73103 headers: { "Content-Type": "application/json" },
74104 body: JSON.stringify({
@@ -77,11 +107,14 @@ export function useThreads() {
77107 maxPromptLength,
78108 userPrompt: userPrompt || null,
79109 }),
110+ errorMessage: "Failed to create thread",
111+ onError,
80112 });
81- if (!res.ok) {
82- throw new Error(`Failed to create thread: ${res.status}`);
113+
114+ if (!data) {
115+ return null;
83116 }
84- const data = await res.json();
117+
85118 const newThread = data.thread;
86119
87120 // Reload threads to get the full list
@@ -97,76 +130,122 @@ export function useThreads() {
97130 }
98131 : undefined,
99132 };
100- } catch (error) {
101- handleError(error, onError);
102- return null;
103- }
104- };
105-
106- const updateThread = async (
107- threadId: number,
108- updates: {
109- model?: string;
110- maxPromptLength?: "none" | 1024 | 4096 | null;
111- title?: string;
112- userPrompt?: string | null;
113133 },
114- onError?: (error: string) => void
115- ): Promise<void> => {
116- try {
117- const res = await fetch(`/api/threads/${threadId}`, {
118- method: "PATCH",
119- headers: { "Content-Type": "application/json" },
120- body: JSON.stringify({
121- ...updates,
122- // Only send title if it's provided
123- ...(updates.title !== undefined ? { title: updates.title } : {}),
124- }),
125- });
126- if (!res.ok) {
127- const errorData = await res.json().catch((parseError) => {
128- throw new Error(getParseErrorMessage(parseError));
134+ [fetchWithErrorHandling, loadThreads]
135+ );
136+
137+ const updateThread = useCallback(
138+ async (
139+ threadId: number,
140+ updates: {
141+ model?: string;
142+ maxPromptLength?: "none" | 1024 | 4096 | null;
143+ title?: string;
144+ userPrompt?: string | null;
145+ },
146+ onError?: (error: string) => void
147+ ): Promise<void> => {
148+ try {
149+ const data = await fetchWithErrorHandling<{ thread: Thread }>(`/api/threads/${threadId}`, {
150+ method: "PATCH",
151+ headers: { "Content-Type": "application/json" },
152+ body: JSON.stringify({
153+ ...updates,
154+ // Only send title if it's provided
155+ ...(updates.title !== undefined ? { title: updates.title } : {}),
156+ }),
157+ errorMessage: "Failed to update thread",
158+ throwOnError: true,
159+ onError,
129160 });
130- throw new Error(errorData.error || "Failed to update thread");
161+
162+ if (data) {
163+ const updatedThread = data.thread;
164+ // Update the thread in local state
165+ setThreads((prev) => prev.map((t) => (t.id === threadId ? updatedThread : t)));
166+ }
167+ } catch (error) {
168+ const errorMsg = getErrorMessage(error, "Failed to update thread");
169+ handleError(errorMsg, onError);
170+ throw error;
131171 }
132- const data = await res.json();
133- const updatedThread = data.thread;
134-
135- // Update the thread in local state
136- setThreads((prev) => prev.map((t) => (t.id === threadId ? updatedThread : t)));
137- } catch (error) {
138- const errorMsg = getErrorMessage(error, "Failed to update thread");
139- handleError(errorMsg, onError);
140- throw error;
141- }
142- };
172+ },
173+ [fetchWithErrorHandling]
174+ );
143175
144- const deleteThread = async (
145- threadId: number,
146- onError?: (error: string) => void
147- ): Promise<void> => {
148- try {
149- const res = await fetch(`/api/threads/${threadId}`, {
150- method: "DELETE",
151- });
152- if (!res.ok) {
153- const errorData = await res.json().catch((parseError) => {
154- throw new Error(getParseErrorMessage(parseError));
176+ const deleteThread = useCallback(
177+ async (threadId: number, onError?: (error: string) => void): Promise<void> => {
178+ try {
179+ await fetchWithErrorHandling(`/api/threads/${threadId}`, {
180+ method: "DELETE",
181+ errorMessage: "Failed to delete thread",
182+ throwOnError: true,
183+ onError,
155184 });
156- throw new Error(errorData.error || "Failed to delete thread");
185+ // Remove the thread from the local state
186+ setThreads((prev) => prev.filter((t) => t.id !== threadId));
187+ setTotalThreadCount((prev) => Math.max(0, prev - 1));
188+ } catch (error) {
189+ const errorMsg = getErrorMessage(error, "Failed to delete thread");
190+ handleError(errorMsg, onError);
191+ throw error;
157192 }
158- // Remove the thread from the local state
159- setThreads((prev) => prev.filter((t) => t.id !== threadId));
160- setTotalThreadCount((prev) => Math.max(0, prev - 1));
161- } catch (error) {
162- const errorMsg = getErrorMessage(error, "Failed to delete thread");
163- handleError(errorMsg, onError);
164- throw error;
165- }
166- };
193+ },
194+ [fetchWithErrorHandling]
195+ );
196+
197+ const handleThreadSelect = useCallback(
198+ (threadId: number) => {
199+ if (config) {
200+ config.setError(null);
201+ config.selectThread(threadId);
202+ }
203+ },
204+ [config]
205+ );
206+
207+ const handleThreadUpdate = useCallback(
208+ async (threadId: number, updates: ThreadUpdates) => {
209+ if (config) {
210+ config.setError(null);
211+ try {
212+ await updateThread(threadId, updates, config.setError);
213+ await loadThreads(8, config.setError);
214+ } catch (error) {
215+ config.setError(getErrorMessage(error));
216+ }
217+ }
218+ },
219+ [config, updateThread, loadThreads]
220+ );
221+
222+ const handleThreadDelete = useCallback(
223+ async (threadId: number) => {
224+ if (config) {
225+ config.setError(null);
226+ try {
227+ await deleteThread(threadId, config.setError);
228+ if (config.currentThreadId === threadId) {
229+ config.deselectThread();
230+ if (config.clearMessagesRef?.current) {
231+ config.clearMessagesRef.current();
232+ }
233+ }
234+ } catch (error) {
235+ config.setError(getErrorMessage(error));
236+ }
237+ }
238+ },
239+ [config, deleteThread]
240+ );
167241
168242 useEffect(() => {
169- loadThreads(8);
243+ if (!hasLoadedRef.current) {
244+ hasLoadedRef.current = true;
245+
246+ void loadThreads(8);
247+ }
248+ // eslint-disable-next-line react-hooks/exhaustive-deps
170249 }, []);
171250
172251 return {
@@ -178,5 +257,8 @@ export function useThreads() {
178257 createThread,
179258 updateThread,
180259 deleteThread,
260+ handleThreadSelect: config ? handleThreadSelect : () => {},
261+ handleThreadUpdate: config ? handleThreadUpdate : async () => {},
262+ handleThreadDelete: config ? handleThreadDelete : async () => {},
181263 };
182264 }