xonecas.io
53129
Pa

PAT / commit ee48e66

refactor: simplify app/page.tsx and ThreadSettingsModal

- extract thread management logic to useThreadManagement hook
- extract model validation to useModelValidation hook
- extract error handling with auto-dismiss to useErrorWithAutoDismiss hook
- extract ThreadSettingsForm component to simplify ThreadSettingsModal
- add memoization with useMemo and useCallback for performance
- reduce app/page.tsx complexity and improve maintainability

xonecas2025-12-19 ee48e66c6d0074977ed43e60d663cc0e88df4419 parent a177b9a

6 files changed

app/page.tsx+89−107
@@ -1,5 +1,5 @@
11 "use client";
2-import { useRef, useState, useEffect } from "react";
2+import { useRef, useMemo, useCallback } 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";
@@ -9,15 +9,16 @@ 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";
12+import { useModelValidation } from "@/src/hooks/useModelValidation";
13+import { useErrorWithAutoDismiss } from "@/src/hooks/useErrorWithAutoDismiss";
14+import { useThreadManagement } from "@/src/hooks/useThreadManagement";
1315 import { getErrorMessage } from "@/src/lib/errors";
1416 import "./highlight-theme.css";
1517
1618 export default function Home() {
17- const [error, setError] = useState<string | null>(null);
19+ const [error, setError] = useErrorWithAutoDismiss();
1820 const { themeMode, handleThemeChange } = useTheme();
1921 const [selectedModel, setSelectedModel] = useLocalStorage<string>("selectedModel", "gpt-oss");
20- const { models } = useModels();
2122 const [maxPromptLength, setMaxPromptLength] = useLocalStorage<"none" | 1024 | 4096>(
2223 "maxPromptLength",
2324 "none"
@@ -26,6 +27,9 @@ export default function Home() {
2627 "newThreadUserPrompt",
2728 ""
2829 );
30+
31+ useModelValidation(selectedModel, setSelectedModel);
32+
2933 const {
3034 threads,
3135 totalThreadCount,
@@ -53,117 +57,99 @@ export default function Home() {
5357 });
5458 const messageInputRef = useRef<MessageInputRef>(null);
5559
56- // Validate and initialize model from localStorage or fetch first available model
57- useEffect(() => {
58- if (models.length === 0) return;
59-
60- // Validate that the saved model still exists
61- if (selectedModel && isValidModel(selectedModel, models)) {
62- return;
63- }
64-
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]);
70-
71- const handleModelChange = (model: string) => {
72- setSelectedModel(model);
73- };
74-
75- const handleMaxPromptLengthChange = (value: "none" | 1024 | 4096) => {
76- setMaxPromptLength(value);
77- };
60+ const { handleThreadSelect, handleThreadUpdate, handleThreadDelete } = useThreadManagement(
61+ updateThread,
62+ deleteThread,
63+ loadThreads,
64+ selectThread,
65+ deselectThread,
66+ clearMessages,
67+ currentThreadId,
68+ setError
69+ );
7870
79- const handleNewThreadUserPromptChange = (userPrompt: string) => {
80- setNewThreadUserPrompt(userPrompt);
81- };
71+ const handleModelChange = useCallback(
72+ (model: string) => {
73+ setSelectedModel(model);
74+ },
75+ [setSelectedModel]
76+ );
8277
83- const handleDeleteMessage = (messageId: number, threadId: number) => {
84- deleteMessageInternal(messageId, threadId, setError);
85- };
78+ const handleMaxPromptLengthChange = useCallback(
79+ (value: "none" | 1024 | 4096) => {
80+ setMaxPromptLength(value);
81+ },
82+ [setMaxPromptLength]
83+ );
8684
87- // Auto-dismiss error after 3 seconds
88- useEffect(() => {
89- if (error) {
90- const timer = setTimeout(() => {
91- setError(null);
92- }, 3000);
93- return () => clearTimeout(timer);
94- }
95- }, [error]);
85+ const handleNewThreadUserPromptChange = useCallback(
86+ (userPrompt: string) => {
87+ setNewThreadUserPrompt(userPrompt);
88+ },
89+ [setNewThreadUserPrompt]
90+ );
9691
97- const handleThreadSelect = (threadId: number) => {
98- setError(null);
99- selectThread(threadId);
100- };
92+ const handleDeleteMessage = useCallback(
93+ (messageId: number, threadId: number) => {
94+ deleteMessageInternal(messageId, threadId, setError);
95+ },
96+ [deleteMessageInternal, setError]
97+ );
10198
102- const handleCreateNewThread = () => {
99+ const handleCreateNewThread = useCallback(() => {
103100 deselectThread();
104101 clearMessages();
105102 setError(null);
106- // Focus the input after a short delay to ensure DOM has updated
107103 setTimeout(() => {
108104 messageInputRef.current?.focus();
109105 }, 0);
110- };
111-
112- const handleThreadUpdate = async (
113- threadId: number,
114- updates: {
115- model?: string;
116- maxPromptLength?: "none" | 1024 | 4096 | null;
117- userPrompt?: string | null;
118- }
119- ) => {
120- setError(null);
121- try {
122- await updateThread(threadId, updates, setError);
123- // Reload threads to ensure UI is in sync
124- await loadThreads(8, setError);
125- } catch (error) {
126- setError(getErrorMessage(error));
127- }
128- };
106+ }, [deselectThread, clearMessages, setError]);
129107
130- const handleThreadDelete = async (threadId: number) => {
131- setError(null);
132- try {
133- await deleteThread(threadId, setError);
134- // If the deleted thread was the current thread, deselect it
135- if (currentThreadId === threadId) {
136- deselectThread();
137- clearMessages();
108+ const handleSendMessage = useCallback(
109+ async (message: string) => {
110+ setError(null);
111+ try {
112+ await sendMessage(
113+ message,
114+ currentThreadId,
115+ (title, firstMessage) =>
116+ createThread(
117+ selectedModel,
118+ maxPromptLength,
119+ title,
120+ firstMessage,
121+ newThreadUserPrompt,
122+ setError
123+ ),
124+ selectThread,
125+ () => loadThreads(8, setError),
126+ setError
127+ );
128+ } catch (error) {
129+ setError(getErrorMessage(error));
138130 }
139- } catch (error) {
140- setError(getErrorMessage(error));
141- }
142- };
131+ },
132+ [
133+ sendMessage,
134+ currentThreadId,
135+ createThread,
136+ selectedModel,
137+ maxPromptLength,
138+ newThreadUserPrompt,
139+ selectThread,
140+ loadThreads,
141+ setError,
142+ ]
143+ );
143144
144- const handleSendMessage = async (message: string) => {
145- setError(null);
146- try {
147- await sendMessage(
148- message,
149- currentThreadId,
150- (title, firstMessage) =>
151- createThread(
152- selectedModel,
153- maxPromptLength,
154- title,
155- firstMessage,
156- newThreadUserPrompt,
157- setError
158- ),
159- selectThread,
160- () => loadThreads(8, setError),
161- setError
162- );
163- } catch (error) {
164- setError(getErrorMessage(error));
165- }
166- };
145+ const currentThread = useMemo(
146+ () => (currentThreadId !== null ? threads.find((t) => t.id === currentThreadId) || null : null),
147+ [currentThreadId, threads]
148+ );
149+
150+ const handleLoadMore = useCallback(() => {
151+ void loadMoreThreads(8, setError);
152+ }, [loadMoreThreads, setError]);
167153
168154 return (
169155 <div className="flex h-screen bg-neutral-100 text-neutral-800 dark:bg-neutral-950 dark:text-neutral-200">
@@ -198,9 +184,7 @@ export default function Home() {
198184 onStop={stopGeneration}
199185 error={error}
200186 currentThreadId={currentThreadId}
201- currentThread={
202- currentThreadId !== null ? threads.find((t) => t.id === currentThreadId) || null : null
203- }
187+ currentThread={currentThread}
204188 onThreadUpdate={handleThreadUpdate}
205189 onThreadDelete={handleThreadDelete}
206190 onError={setError}
@@ -219,9 +203,7 @@ export default function Home() {
219203 onCreateNewThread={handleCreateNewThread}
220204 onThreadSelect={handleThreadSelect}
221205 onThemeChange={handleThemeChange}
222- onLoadMore={() => {
223- void loadMoreThreads(8, setError);
224- }}
206+ onLoadMore={handleLoadMore}
225207 hasMoreThreads={hasMoreThreads}
226208 totalThreadCount={totalThreadCount}
227209 />
src/components/ThreadSettingsForm.tsx+94−0
@@ -0,0 +1,94 @@
1+"use client";
2+
3+import type { Model } from "@/src/hooks/useModels";
4+
5+type ThreadSettingsFormProps = {
6+ models: Model[];
7+ isLoadingModels: boolean;
8+ selectedModel: string;
9+ onModelChange: (model: string) => void;
10+ maxPromptLength: "none" | 1024 | 4096 | null;
11+ onMaxPromptLengthChange: (value: "none" | 1024 | 4096 | null) => void;
12+ userPrompt: string;
13+ onUserPromptChange: (userPrompt: string) => void;
14+ isNewThread: boolean;
15+};
16+
17+/**
18+ * Shared form fields for thread settings (both new and existing threads).
19+ */
20+export default function ThreadSettingsForm({
21+ models,
22+ isLoadingModels,
23+ selectedModel,
24+ onModelChange,
25+ maxPromptLength,
26+ onMaxPromptLengthChange,
27+ userPrompt,
28+ onUserPromptChange,
29+ isNewThread,
30+}: ThreadSettingsFormProps) {
31+ return (
32+ <div className="flex flex-col gap-4">
33+ <div className="flex flex-col gap-2">
34+ <label className="text-sm font-medium text-neutral-600 dark:text-neutral-400">Model</label>
35+ <select
36+ value={selectedModel}
37+ onChange={(e) => onModelChange(e.target.value)}
38+ disabled={isLoadingModels}
39+ className="bg-white px-3 py-2 text-neutral-800 focus:outline-none disabled:opacity-50 dark:bg-neutral-950 dark:text-neutral-200"
40+ >
41+ {isLoadingModels ? (
42+ <option>Loading models...</option>
43+ ) : models.length === 0 ? (
44+ <option>No models available</option>
45+ ) : (
46+ models.map((model) => (
47+ <option key={model.name} value={model.model}>
48+ {model.name}
49+ </option>
50+ ))
51+ )}
52+ </select>
53+ </div>
54+
55+ <div className="flex flex-col gap-2">
56+ <label className="text-sm font-medium text-neutral-600 dark:text-neutral-400">
57+ Max Prompt Length
58+ </label>
59+ <select
60+ value={maxPromptLength === null ? "none" : maxPromptLength}
61+ onChange={(e) =>
62+ onMaxPromptLengthChange(
63+ e.target.value === "none" ? null : (parseInt(e.target.value, 10) as 1024 | 4096)
64+ )
65+ }
66+ className="bg-white px-3 py-2 text-neutral-800 focus:outline-none dark:bg-neutral-950 dark:text-neutral-200"
67+ >
68+ <option value="none">None</option>
69+ <option value="1024">1024</option>
70+ <option value="4096">4096</option>
71+ </select>
72+ </div>
73+
74+ <div className="flex flex-col gap-2">
75+ <label className="text-sm font-medium text-neutral-600 dark:text-neutral-400">
76+ User Prompt
77+ </label>
78+ <textarea
79+ value={userPrompt}
80+ onChange={(e) => onUserPromptChange(e.target.value)}
81+ placeholder="Additional instructions or information for the assistant..."
82+ rows={4}
83+ disabled={!isNewThread}
84+ className="bg-white px-3 py-2 text-neutral-800 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 dark:bg-neutral-950 dark:text-neutral-200"
85+ />
86+ {!isNewThread && (
87+ <p className="text-xs text-neutral-500 dark:text-neutral-500">
88+ User prompt can only be set when creating a new thread.
89+ </p>
90+ )}
91+ </div>
92+ </div>
93+ );
94+}
src/components/ThreadSettingsModal.tsx+37−84
@@ -1,9 +1,10 @@
11 "use client";
22
3-import { useState, useEffect } from "react";
3+import { useState, useEffect, useMemo } from "react";
44 import Modal from "@/src/components/Modal";
55 import SecondaryButton from "@/src/components/buttons/SecondaryButton";
66 import TrashIcon from "@/src/components/icons/TrashIcon";
7+import ThreadSettingsForm from "@/src/components/ThreadSettingsForm";
78 import type { Thread } from "@/src/lib/db/schema";
89 import { useModels } from "@/src/hooks/useModels";
910 import { handleError } from "@/src/lib/errors";
@@ -68,38 +69,34 @@ export default function ThreadSettingsModal({
6869 }
6970 }, [thread, isOpen, isNewThread, initialModel, initialMaxPromptLength, initialUserPrompt]);
7071
72+ const hasChanges = useMemo(() => {
73+ if (isNewThread) return true;
74+ if (!thread) return false;
75+ return (
76+ selectedModel !== (thread.model || "gpt-oss") ||
77+ maxPromptLength !==
78+ (thread.maxPromptLength === null ? "none" : (thread.maxPromptLength as 1024 | 4096))
79+ );
80+ }, [isNewThread, thread, selectedModel, maxPromptLength]);
81+
7182 const handleSave = async () => {
7283 if (isNewThread) {
73- // For new thread, just update the parent's state
74- if (onModelChange) {
75- onModelChange(selectedModel);
76- }
77- if (onMaxPromptLengthChange && maxPromptLength !== null) {
78- onMaxPromptLengthChange(maxPromptLength === "none" ? "none" : maxPromptLength);
79- }
80- if (onUserPromptChange) {
81- onUserPromptChange(userPrompt);
84+ onModelChange?.(selectedModel);
85+ if (maxPromptLength !== null) {
86+ onMaxPromptLengthChange?.(maxPromptLength === "none" ? "none" : maxPromptLength);
8287 }
88+ onUserPromptChange?.(userPrompt);
8389 onClose();
8490 return;
8591 }
8692
87- if (!thread || !onUpdateThread) return;
88-
89- const hasChanges =
90- selectedModel !== (thread.model || "gpt-oss") ||
91- maxPromptLength !==
92- (thread.maxPromptLength === null ? "none" : (thread.maxPromptLength as 1024 | 4096));
93-
94- // If there are no changes, just close the modal
95- if (!hasChanges) {
93+ if (!thread || !onUpdateThread || !hasChanges) {
9694 onClose();
9795 return;
9896 }
9997
10098 setIsSaving(true);
10199 try {
102- // Don't send userPrompt for existing threads - it's read-only
103100 await onUpdateThread(thread.id, {
104101 model: selectedModel,
105102 maxPromptLength: maxPromptLength === "none" ? null : maxPromptLength,
@@ -126,7 +123,15 @@ export default function ThreadSettingsModal({
126123 }
127124 };
128125
129- const threadTitle = thread ? thread.title || `Thread ${thread.id}` : null;
126+ const threadTitle = useMemo(
127+ () => (thread ? thread.title || `Thread ${thread.id}` : null),
128+ [thread]
129+ );
130+
131+ const handleModelChange = (model: string) => setSelectedModel(model);
132+ const handleMaxPromptLengthChange = (value: "none" | 1024 | 4096 | null) =>
133+ setMaxPromptLength(value);
134+ const handleUserPromptChange = (prompt: string) => setUserPrompt(prompt);
130135
131136 return (
132137 <Modal isOpen={isOpen} onClose={onClose}>
@@ -138,69 +143,17 @@ export default function ThreadSettingsModal({
138143 <p className="text-sm text-neutral-600 dark:text-neutral-400">{threadTitle}</p>
139144 )}
140145
141- <div className="flex flex-col gap-4">
142- <div className="flex flex-col gap-2">
143- <label className="text-sm font-medium text-neutral-600 dark:text-neutral-400">
144- Model
145- </label>
146- <select
147- value={selectedModel}
148- onChange={(e) => setSelectedModel(e.target.value)}
149- disabled={isLoadingModels}
150- className="bg-white px-3 py-2 text-neutral-800 focus:outline-none disabled:opacity-50 dark:bg-neutral-950 dark:text-neutral-200"
151- >
152- {isLoadingModels ? (
153- <option>Loading models...</option>
154- ) : models.length === 0 ? (
155- <option>No models available</option>
156- ) : (
157- models.map((model) => (
158- <option key={model.name} value={model.model}>
159- {model.name}
160- </option>
161- ))
162- )}
163- </select>
164- </div>
165-
166- <div className="flex flex-col gap-2">
167- <label className="text-sm font-medium text-neutral-600 dark:text-neutral-400">
168- Max Prompt Length
169- </label>
170- <select
171- value={maxPromptLength === null ? "none" : maxPromptLength}
172- onChange={(e) =>
173- setMaxPromptLength(
174- e.target.value === "none" ? "none" : (parseInt(e.target.value, 10) as 1024 | 4096)
175- )
176- }
177- className="bg-white px-3 py-2 text-neutral-800 focus:outline-none dark:bg-neutral-950 dark:text-neutral-200"
178- >
179- <option value="none">None</option>
180- <option value="1024">1024</option>
181- <option value="4096">4096</option>
182- </select>
183- </div>
184-
185- <div className="flex flex-col gap-2">
186- <label className="text-sm font-medium text-neutral-600 dark:text-neutral-400">
187- User Prompt
188- </label>
189- <textarea
190- value={userPrompt}
191- onChange={(e) => setUserPrompt(e.target.value)}
192- placeholder="Additional instructions or information for the assistant..."
193- rows={4}
194- disabled={!isNewThread}
195- className="bg-white px-3 py-2 text-neutral-800 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 dark:bg-neutral-950 dark:text-neutral-200"
196- />
197- {!isNewThread && (
198- <p className="text-xs text-neutral-500 dark:text-neutral-500">
199- User prompt can only be set when creating a new thread.
200- </p>
201- )}
202- </div>
203- </div>
146+ <ThreadSettingsForm
147+ models={models}
148+ isLoadingModels={isLoadingModels}
149+ selectedModel={selectedModel}
150+ onModelChange={handleModelChange}
151+ maxPromptLength={maxPromptLength}
152+ onMaxPromptLengthChange={handleMaxPromptLengthChange}
153+ userPrompt={userPrompt}
154+ onUserPromptChange={handleUserPromptChange}
155+ isNewThread={isNewThread}
156+ />
204157
205158 <div className="flex justify-between gap-2 border-t border-neutral-300 pt-4 dark:border-neutral-700">
206159 {!isNewThread && onDeleteThread && (
src/hooks/useErrorWithAutoDismiss.ts+25−0
@@ -0,0 +1,25 @@
1+import { useState, useEffect } from "react";
2+
3+/**
4+ * Custom hook for managing error state with automatic dismissal.
5+ * Errors are automatically cleared after a specified duration.
6+ *
7+ * @param dismissAfterMs - Time in milliseconds before auto-dismissing (default: 3000)
8+ * @returns Tuple of [error, setError] similar to useState
9+ */
10+export function useErrorWithAutoDismiss(
11+ dismissAfterMs = 3000
12+): [string | null, (error: string | null) => void] {
13+ const [error, setError] = useState<string | null>(null);
14+
15+ useEffect(() => {
16+ if (error) {
17+ const timer = setTimeout(() => {
18+ setError(null);
19+ }, dismissAfterMs);
20+ return () => clearTimeout(timer);
21+ }
22+ }, [error, dismissAfterMs]);
23+
24+ return [error, setError];
25+}
src/hooks/useModelValidation.ts+30−0
@@ -0,0 +1,30 @@
1+import { useEffect } from "react";
2+import { useModels, isValidModel } from "./useModels";
3+
4+/**
5+ * Custom hook for validating and initializing model selection.
6+ * Automatically selects the first available model if the current selection is invalid.
7+ *
8+ * @param selectedModel - The currently selected model
9+ * @param setSelectedModel - Function to update the selected model
10+ */
11+export function useModelValidation(
12+ selectedModel: string,
13+ setSelectedModel: (model: string) => void
14+): void {
15+ const { models } = useModels();
16+
17+ useEffect(() => {
18+ if (models.length === 0) return;
19+
20+ // Validate that the saved model still exists
21+ if (selectedModel && isValidModel(selectedModel, models)) {
22+ return;
23+ }
24+
25+ // If no saved model or it doesn't exist, get first available
26+ if (models.length > 0) {
27+ setSelectedModel(models[0].model);
28+ }
29+ }, [models, selectedModel, setSelectedModel]);
30+}
src/hooks/useThreadManagement.ts+81−0
@@ -0,0 +1,81 @@
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+}