xonecas.io
53129
Pa

PAT / commit 65643c8

feat: settings refactor

xonecas2025-12-19 65643c8ecdcfbd0b9aaf60954b9fbceb1bad6b69 parent 6439350

12 files changed

app/api/settings/route.ts+2−31
@@ -1,12 +1,9 @@
11 import { NextResponse } from "next/server";
22 import { getCache, setCache } from "@/src/lib/cache";
3-import { getFirstAvailableModel } from "@/src/lib/ollama/models";
43
54 const SETTINGS_CACHE_KEY = "app_settings";
65
76 type Settings = {
8- maxPromptLength: "none" | 1024 | 4096;
9- selectedModel?: string;
107 location?: string;
118 currentTime?: string;
129 timezone?: string;
@@ -19,12 +16,7 @@ export async function GET() {
1916 return NextResponse.json({ settings });
2017 }
2118
22- // If no settings exist, get the first available model
23- const firstModel = await getFirstAvailableModel();
24- const defaultSettings: Settings = {
25- maxPromptLength: "none",
26- selectedModel: firstModel || undefined,
27- };
19+ const defaultSettings: Settings = {};
2820
2921 return NextResponse.json({ settings: defaultSettings });
3022 } catch {
@@ -34,26 +26,10 @@ export async function GET() {
3426
3527 export async function POST(request: Request) {
3628 try {
37- const { maxPromptLength, selectedModel, location, currentTime, timezone } = await request.json();
29+ const { location, currentTime, timezone } = await request.json();
3830
3931 let settings: Partial<Settings> = {};
4032
41- // Validate and set maxPromptLength if provided
42- if (maxPromptLength !== undefined) {
43- if (maxPromptLength !== "none" && maxPromptLength !== 1024 && maxPromptLength !== 4096) {
44- return NextResponse.json({ error: "Invalid maxPromptLength value" }, { status: 400 });
45- }
46- settings.maxPromptLength = maxPromptLength;
47- }
48-
49- // Validate and set selectedModel if provided
50- if (selectedModel !== undefined) {
51- if (typeof selectedModel !== "string") {
52- return NextResponse.json({ error: "Invalid selectedModel value" }, { status: 400 });
53- }
54- settings.selectedModel = selectedModel;
55- }
56-
5733 // Validate and set location if provided
5834 if (location !== undefined) {
5935 if (typeof location !== "string") {
@@ -84,11 +60,6 @@ export async function POST(request: Request) {
8460 settings = { ...existingSettings, ...settings };
8561 }
8662
87- if (!settings.selectedModel) {
88- const firstModel = await getFirstAvailableModel();
89- settings.selectedModel = firstModel;
90- }
91-
9263 // Update the cache with new settings.
9364 await setCache(SETTINGS_CACHE_KEY, settings);
9465
app/api/threads/route.ts+9−2
@@ -7,8 +7,6 @@ import { getCache } from "@/src/lib/cache";
77 const SETTINGS_CACHE_KEY = "app_settings";
88
99 type Settings = {
10- maxPromptLength: "none" | 1024 | 4096;
11- selectedModel?: string;
1210 location?: string;
1311 currentTime?: string;
1412 timezone?: string;
@@ -17,6 +15,15 @@ type Settings = {
1715 export async function POST(request: Request) {
1816 try {
1917 const { title, model, maxPromptLength } = await request.json();
18+
19+ // Validate required parameters
20+ if (!model || typeof model !== "string") {
21+ return NextResponse.json({ error: "model is required" }, { status: 400 });
22+ }
23+ if (maxPromptLength === undefined) {
24+ return NextResponse.json({ error: "maxPromptLength is required" }, { status: 400 });
25+ }
26+
2027 const newThread = await db
2128 .insert(threads)
2229 .values({
app/page.tsx+64−18
@@ -14,14 +14,9 @@ import "./highlight-theme.css";
1414 export default function Home() {
1515 const [error, setError] = useState<string | null>(null);
1616 const { themeMode, handleThemeChange } = useTheme();
17- const {
18- selectedModel,
19- handleModelChange,
20- maxPromptLength,
21- handleMaxPromptLengthChange,
22- location,
23- handleLocationChange,
24- } = useSettings(setError);
17+ const { location, handleLocationChange } = useSettings(setError);
18+ const [selectedModel, setSelectedModel] = useState<string>("gpt-oss");
19+ const [maxPromptLength, setMaxPromptLength] = useState<"none" | 1024 | 4096>("none");
2520 const {
2621 threads,
2722 totalThreadCount,
@@ -49,6 +44,60 @@ export default function Home() {
4944 });
5045 const messageInputRef = useRef<MessageInputRef>(null);
5146
47+ // Initialize model from localStorage or fetch first available model
48+ useEffect(() => {
49+ const initializeModel = async () => {
50+ // Check localStorage for previously selected model
51+ const savedModel = localStorage.getItem("selectedModel");
52+ if (savedModel) {
53+ // Validate that the model still exists
54+ try {
55+ const res = await fetch("/api/models");
56+ if (res.ok) {
57+ const data = await res.json();
58+ const availableModels = data.models || [];
59+ const modelExists = availableModels.some(
60+ (m: { name: string; model: string }) => m.model === savedModel
61+ );
62+ if (modelExists) {
63+ setSelectedModel(savedModel);
64+ return;
65+ }
66+ }
67+ } catch {
68+ // Fall through to default
69+ }
70+ }
71+
72+ // If no saved model or it doesn't exist, get first available
73+ try {
74+ const res = await fetch("/api/models");
75+ if (res.ok) {
76+ const data = await res.json();
77+ const availableModels = data.models || [];
78+ if (availableModels.length > 0) {
79+ const firstModel = availableModels[0].model;
80+ setSelectedModel(firstModel);
81+ localStorage.setItem("selectedModel", firstModel);
82+ }
83+ }
84+ } catch {
85+ // Keep default
86+ }
87+ };
88+
89+ initializeModel();
90+ }, []);
91+
92+ const handleModelChange = (model: string) => {
93+ setSelectedModel(model);
94+ localStorage.setItem("selectedModel", model);
95+ };
96+
97+ const handleMaxPromptLengthChange = (value: "none" | 1024 | 4096) => {
98+ setMaxPromptLength(value);
99+ };
100+
52101 const handleDeleteMessage = (messageId: number, threadId: number) => {
53102 deleteMessageInternal(messageId, threadId, setError);
54103 };
@@ -116,8 +165,8 @@ export default function Home() {
116165 await sendMessage(
117166 message,
118167 currentThreadId,
119- (title, firstMessage, model, maxPromptLength) =>
120- createThread(title, firstMessage, model, maxPromptLength, setError),
168+ (title, firstMessage) =>
169+ createThread(title, firstMessage, selectedModel, maxPromptLength, setError),
121170 selectThread,
122171 () => loadThreads(8, setError),
123172 selectedModel,
@@ -144,14 +193,7 @@ export default function Home() {
144193 className={`mx-auto flex min-h-full max-w-5xl flex-col gap-8 ${currentThreadId === null ? "justify-center" : "justify-end"}`}
145194 >
146195 {currentThreadId === null ? (
147- <NoThreadSelected
148- threadCount={totalThreadCount}
149- selectedModel={selectedModel}
150- onModelChange={handleModelChange}
151- maxPromptLength={maxPromptLength}
152- onMaxPromptLengthChange={handleMaxPromptLengthChange}
153- onError={setError}
154- />
196+ <NoThreadSelected threadCount={totalThreadCount} />
155197 ) : (
156198 <MessageList
157199 messages={messages}
@@ -177,6 +219,10 @@ export default function Home() {
177219 onThreadUpdate={handleThreadUpdate}
178220 onThreadDelete={handleThreadDelete}
179221 onError={setError}
222+ newThreadModel={selectedModel}
223+ newThreadMaxPromptLength={maxPromptLength}
224+ onNewThreadModelChange={handleModelChange}
225+ onNewThreadMaxPromptLengthChange={handleMaxPromptLengthChange}
180226 />
181227 </div>
182228 <Sidebar
src/components/MessageInput.tsx+19−2
@@ -25,6 +25,10 @@ type MessageInputProps = {
2525 ) => Promise<void>;
2626 onThreadDelete?: (threadId: number) => Promise<void>;
2727 onError?: (error: string) => void;
28+ newThreadModel?: string;
29+ newThreadMaxPromptLength?: "none" | 1024 | 4096;
30+ onNewThreadModelChange?: (model: string) => void;
31+ onNewThreadMaxPromptLengthChange?: (value: "none" | 1024 | 4096) => void;
2832 };
2933
3034 export type MessageInputRef = {
@@ -46,6 +50,10 @@ const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
4650 onThreadUpdate,
4751 onThreadDelete,
4852 onError,
53+ newThreadModel,
54+ newThreadMaxPromptLength,
55+ onNewThreadModelChange,
56+ onNewThreadMaxPromptLengthChange,
4957 },
5058 ref
5159 ) => {
@@ -153,14 +161,23 @@ const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
153161 {error && <ErrorNotification message={error} />}
154162 </div>
155163 <div className="flex items-center justify-end">
156- {currentThreadId !== null && currentThread && onThreadUpdate && onThreadDelete && (
164+ {currentThreadId !== null && currentThread && onThreadUpdate && onThreadDelete ? (
157165 <ThreadSettingsButton
158166 thread={currentThread}
159167 onUpdateThread={onThreadUpdate}
160168 onDeleteThread={onThreadDelete}
161169 onError={onError}
162170 />
163- )}
171+ ) : currentThreadId === null && onNewThreadModelChange && onNewThreadMaxPromptLengthChange ? (
172+ <ThreadSettingsButton
173+ thread={null}
174+ initialModel={newThreadModel}
175+ initialMaxPromptLength={newThreadMaxPromptLength}
176+ onModelChange={onNewThreadModelChange}
177+ onMaxPromptLengthChange={onNewThreadMaxPromptLengthChange}
178+ onError={onError}
179+ />
180+ ) : null}
164181 </div>
165182 </div>
166183 <form
src/components/Modal.tsx+1−1
@@ -42,7 +42,7 @@ export default function Modal({ isOpen, onClose, children }: ModalProps) {
4242 <XIcon className="h-5 w-5" />
4343 </button>
4444 {/* Content */}
45- <div className="pr-8">{children}</div>
45+ <div>{children}</div>
4646 </div>
4747 </div>
4848 );
src/components/NoThreadSelected.tsx+0−91
@@ -4,24 +4,12 @@ import { useState, useEffect } from "react";
44
55 type NoThreadSelectedProps = {
66 threadCount: number;
7- selectedModel: string;
8- onModelChange: (model: string) => void;
9- maxPromptLength: "none" | 1024 | 4096;
10- onMaxPromptLengthChange: (value: "none" | 1024 | 4096) => void;
11- onError?: (error: string) => void;
127 };
138
149 export default function NoThreadSelected({
1510 threadCount,
16- selectedModel,
17- onModelChange,
18- maxPromptLength,
19- onMaxPromptLengthChange,
20- onError,
2111 }: NoThreadSelectedProps) {
2212 const [currentTime, setCurrentTime] = useState<Date | null>(null);
23- const [models, setModels] = useState<Array<{ name: string; model: string }>>([]);
24- const [isLoadingModels, setIsLoadingModels] = useState(false);
2513
2614 useEffect(() => {
2715 // Set initial time only on client after hydration
@@ -33,41 +21,6 @@ export default function NoThreadSelected({
3321 return () => clearInterval(timer);
3422 }, []);
3523
36- useEffect(() => {
37- let cancelled = false;
38- const loadModels = async () => {
39- setIsLoadingModels(true);
40- try {
41- const res = await fetch("/api/models");
42- if (!res.ok) {
43- const errorData = await res.json().catch((parseError) => {
44- throw new Error(
45- `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
46- );
47- });
48- throw new Error(errorData.error || res.statusText);
49- }
50- const data = await res.json();
51- if (!cancelled) {
52- const availableModels = data.models || [];
53- setModels(availableModels);
54- setIsLoadingModels(false);
55- }
56- } catch (error) {
57- if (!cancelled) {
58- setIsLoadingModels(false);
59- if (onError && error instanceof Error) {
60- onError(error.message);
61- }
62- }
63- }
64- };
65- loadModels();
66- return () => {
67- cancelled = true;
68- };
69- }, [onError]);
70-
7124 const formatTime = (date: Date): string => {
7225 return date.toLocaleString();
7326 };
@@ -84,50 +37,6 @@ export default function NoThreadSelected({
8437 sidebar.
8538 </p>
8639 <hr className="border-neutral-300 dark:border-neutral-700" />
87- <div className="flex flex-col gap-4">
88- <div className="flex flex-col gap-2">
89- <label className="text-sm font-medium text-neutral-600 dark:text-neutral-400">
90- Model
91- </label>
92- <select
93- value={selectedModel}
94- onChange={(e) => onModelChange(e.target.value)}
95- disabled={isLoadingModels}
96- className="bg-neutral-100 px-3 py-2 text-neutral-800 focus:outline-none disabled:opacity-50 dark:bg-neutral-900 dark:text-neutral-200"
97- >
98- {isLoadingModels ? (
99- <option>Loading models...</option>
100- ) : models.length === 0 ? (
101- <option>No models available</option>
102- ) : (
103- models.map((model) => (
104- <option key={model.name} value={model.model}>
105- {model.name}
106- </option>
107- ))
108- )}
109- </select>
110- </div>
111- <div className="flex flex-col gap-2">
112- <label className="text-sm font-medium text-neutral-600 dark:text-neutral-400">
113- Max Prompt Length
114- </label>
115- <select
116- value={maxPromptLength}
117- onChange={(e) =>
118- onMaxPromptLengthChange(
119- e.target.value === "none" ? "none" : (parseInt(e.target.value, 10) as 1024 | 4096)
120- )
121- }
122- className="bg-neutral-100 px-3 py-2 text-neutral-800 focus:outline-none dark:bg-neutral-900 dark:text-neutral-200"
123- >
124- <option value="none">None</option>
125- <option value="1024">1024</option>
126- <option value="4096">4096</option>
127- </select>
128- </div>
129- </div>
130- <hr className="border-neutral-300 dark:border-neutral-700" />
13140 <p className="text-sm text-neutral-600 dark:text-neutral-400">
13241 {timeDisplay && (
13342 <>
src/components/SettingsModal.tsx+2−2
@@ -30,7 +30,7 @@ export default function SettingsModal({
3030 <select
3131 value={themeMode}
3232 onChange={(e) => onThemeChange(e.target.value as "device" | "dark" | "light")}
33- className="bg-neutral-100 px-3 py-1 text-neutral-800 focus:outline-none dark:bg-neutral-900 dark:text-neutral-200"
33+ className="bg-white px-3 py-1 text-neutral-800 focus:outline-none dark:bg-neutral-950 dark:text-neutral-200"
3434 >
3535 <option value="device">Device</option>
3636 <option value="dark">Dark</option>
@@ -44,7 +44,7 @@ export default function SettingsModal({
4444 value={location}
4545 onChange={(e) => onLocationChange(e.target.value)}
4646 placeholder="Enter location name (e.g., New York, London)"
47- className="bg-neutral-100 px-3 py-1 text-neutral-800 focus:outline-none dark:bg-neutral-900 dark:text-neutral-200"
47+ className="bg-white px-3 py-1 text-neutral-800 focus:outline-none dark:bg-neutral-950 dark:text-neutral-200"
4848 />
4949 </div>
5050 </div>
src/components/ThreadSettingsButton.tsx+15−3
@@ -6,13 +6,17 @@ import ThreadSettingsModal from "@/src/components/ThreadSettingsModal";
66 import type { Thread } from "@/src/lib/db/schema";
77
88 type ThreadSettingsButtonProps = {
9- thread: Thread;
10- onUpdateThread: (
9+ thread: Thread | null;
10+ onUpdateThread?: (
1111 threadId: number,
1212 updates: { model?: string; maxPromptLength?: "none" | 1024 | 4096 | null }
1313 ) => Promise<void>;
14- onDeleteThread: (threadId: number) => Promise<void>;
14+ onDeleteThread?: (threadId: number) => Promise<void>;
1515 onError?: (error: string) => void;
16+ initialModel?: string;
17+ initialMaxPromptLength?: "none" | 1024 | 4096;
18+ onModelChange?: (model: string) => void;
19+ onMaxPromptLengthChange?: (value: "none" | 1024 | 4096) => void;
1620 };
1721
1822 export default function ThreadSettingsButton({
@@ -20,6 +24,10 @@ export default function ThreadSettingsButton({
2024 onUpdateThread,
2125 onDeleteThread,
2226 onError,
27+ initialModel,
28+ initialMaxPromptLength,
29+ onModelChange,
30+ onMaxPromptLengthChange,
2331 }: ThreadSettingsButtonProps) {
2432 const [isModalOpen, setIsModalOpen] = useState(false);
2533
@@ -44,6 +52,10 @@ export default function ThreadSettingsButton({
4452 onUpdateThread={onUpdateThread}
4553 onDeleteThread={onDeleteThread}
4654 onError={onError}
55+ initialModel={initialModel}
56+ initialMaxPromptLength={initialMaxPromptLength}
57+ onModelChange={onModelChange}
58+ onMaxPromptLengthChange={onMaxPromptLengthChange}
4759 />
4860 </>
4961 );
src/components/ThreadSettingsModal.tsx+58−29
@@ -11,12 +11,16 @@ type ThreadSettingsModalProps = {
1111 isOpen: boolean;
1212 onClose: () => void;
1313 thread: Thread | null;
14- onUpdateThread: (
14+ onUpdateThread?: (
1515 threadId: number,
1616 updates: { model?: string; maxPromptLength?: "none" | 1024 | 4096 | null }
1717 ) => Promise<void>;
18- onDeleteThread: (threadId: number) => Promise<void>;
18+ onDeleteThread?: (threadId: number) => Promise<void>;
1919 onError?: (error: string) => void;
20+ initialModel?: string;
21+ initialMaxPromptLength?: "none" | 1024 | 4096;
22+ onModelChange?: (model: string) => void;
23+ onMaxPromptLengthChange?: (value: "none" | 1024 | 4096) => void;
2024 };
2125
2226 export default function ThreadSettingsModal({
@@ -26,6 +30,10 @@ export default function ThreadSettingsModal({
2630 onUpdateThread,
2731 onDeleteThread,
2832 onError,
33+ initialModel,
34+ initialMaxPromptLength,
35+ onModelChange,
36+ onMaxPromptLengthChange,
2937 }: ThreadSettingsModalProps) {
3038 const [models, setModels] = useState<Array<{ name: string; model: string }>>([]);
3139 const [isLoadingModels, setIsLoadingModels] = useState(false);
@@ -33,6 +41,7 @@ export default function ThreadSettingsModal({
3341 const [maxPromptLength, setMaxPromptLength] = useState<"none" | 1024 | 4096 | null>("none");
3442 const [isSaving, setIsSaving] = useState(false);
3543 const [isDeleting, setIsDeleting] = useState(false);
44+ const isNewThread = thread === null;
3645
3746 // Load models when modal opens
3847 useEffect(() => {
@@ -64,18 +73,34 @@ export default function ThreadSettingsModal({
6473 }
6574 }, [isOpen, onError]);
6675
67- // Load thread settings when thread changes
76+ // Load thread settings when thread changes or when modal opens for new thread
6877 useEffect(() => {
6978 if (thread) {
7079 setSelectedModel(thread.model || "gpt-oss");
7180 setMaxPromptLength(
7281 thread.maxPromptLength === null ? "none" : (thread.maxPromptLength as 1024 | 4096)
7382 );
83+ } else if (isOpen && isNewThread) {
84+ // For new thread, use initial values or defaults
85+ setSelectedModel(initialModel || "gpt-oss");
86+ setMaxPromptLength(initialMaxPromptLength || "none");
7487 }
75- }, [thread]);
88+ }, [thread, isOpen, isNewThread, initialModel, initialMaxPromptLength]);
7689
7790 const handleSave = async () => {
78- if (!thread) return;
91+ if (isNewThread) {
92+ // For new thread, just update the parent's state
93+ if (onModelChange) {
94+ onModelChange(selectedModel);
95+ }
96+ if (onMaxPromptLengthChange && maxPromptLength !== null) {
97+ onMaxPromptLengthChange(maxPromptLength === "none" ? "none" : maxPromptLength);
98+ }
99+ onClose();
100+ return;
101+ }
102+
103+ if (!thread || !onUpdateThread) return;
79104
80105 const hasChanges =
81106 selectedModel !== (thread.model || "gpt-oss") ||
@@ -105,7 +130,7 @@ export default function ThreadSettingsModal({
105130 };
106131
107132 const handleDelete = async () => {
108- if (!thread) return;
133+ if (!thread || !onDeleteThread) return;
109134
110135 setIsDeleting(true);
111136 try {
@@ -120,17 +145,17 @@ export default function ThreadSettingsModal({
120145 }
121146 };
122147
123- if (!thread) {
124- return null;
125- }
126-
127- const threadTitle = thread.title || `Thread ${thread.id}`;
148+ const threadTitle = thread ? (thread.title || `Thread ${thread.id}`) : null;
128149
129150 return (
130151 <Modal isOpen={isOpen} onClose={onClose}>
131152 <div className="flex flex-col gap-4">
132- <h2 className="text-xl font-semibold">Thread Settings</h2>
133- <p className="text-sm text-neutral-600 dark:text-neutral-400">{threadTitle}</p>
153+ <h2 className="text-xl font-semibold">
154+ {isNewThread ? "New Thread Settings" : "Thread Settings"}
155+ </h2>
156+ {threadTitle && (
157+ <p className="text-sm text-neutral-600 dark:text-neutral-400">{threadTitle}</p>
158+ )}
134159
135160 <div className="flex flex-col gap-4">
136161 <div className="flex flex-col gap-2">
@@ -141,7 +166,7 @@ export default function ThreadSettingsModal({
141166 value={selectedModel}
142167 onChange={(e) => setSelectedModel(e.target.value)}
143168 disabled={isLoadingModels}
144- className="bg-neutral-100 px-3 py-2 text-neutral-800 focus:outline-none disabled:opacity-50 dark:bg-neutral-900 dark:text-neutral-200"
169+ className="bg-white px-3 py-2 text-neutral-800 focus:outline-none disabled:opacity-50 dark:bg-neutral-950 dark:text-neutral-200"
145170 >
146171 {isLoadingModels ? (
147172 <option>Loading models...</option>
@@ -168,7 +193,7 @@ export default function ThreadSettingsModal({
168193 e.target.value === "none" ? "none" : (parseInt(e.target.value, 10) as 1024 | 4096)
169194 )
170195 }
171- className="bg-neutral-100 px-3 py-2 text-neutral-800 focus:outline-none dark:bg-neutral-900 dark:text-neutral-200"
196+ className="bg-white px-3 py-2 text-neutral-800 focus:outline-none dark:bg-neutral-950 dark:text-neutral-200"
172197 >
173198 <option value="none">None</option>
174199 <option value="1024">1024</option>
@@ -178,28 +203,32 @@ export default function ThreadSettingsModal({
178203 </div>
179204
180205 <div className="flex justify-between gap-2 border-t border-neutral-300 pt-4 dark:border-neutral-700">
181- <SecondaryButton
182- onClick={(e) => {
183- e.preventDefault();
184- if (!isDeleting && !isSaving) {
185- handleDelete();
186- }
187- }}
188- className={isDeleting || isSaving ? "cursor-not-allowed opacity-50" : ""}
189- >
190- <TrashIcon className="h-4 w-4" />
191- {isDeleting ? "Deleting..." : "Delete Thread"}
192- </SecondaryButton>
206+ {!isNewThread && onDeleteThread && (
207+ <SecondaryButton
208+ onClick={(e) => {
209+ e.preventDefault();
210+ if (!isDeleting && !isSaving) {
211+ handleDelete();
212+ }
213+ }}
214+ className={isDeleting || isSaving ? "cursor-not-allowed opacity-50" : ""}
215+ >
216+ <TrashIcon className="h-4 w-4" />
217+ {isDeleting ? "Deleting..." : "Delete Thread"}
218+ </SecondaryButton>
219+ )}
220+ {isNewThread && <div />}
193221 <div className="flex gap-2">
194- <PrimaryButton
222+ <SecondaryButton
195223 onClick={(e) => {
196224 e.preventDefault();
197225 handleSave();
198226 }}
199227 disabled={isSaving || isDeleting}
228+ color="neutral"
200229 >
201230 {isSaving ? "Saving..." : "Save"}
202- </PrimaryButton>
231+ </SecondaryButton>
203232 </div>
204233 </div>
205234 </div>
src/hooks/useMessages.ts+3−7
@@ -49,9 +49,7 @@ export function useMessages(
4949 currentThreadId: number | null,
5050 onCreateThread: (
5151 title?: string,
52- firstMessage?: string,
53- model?: string,
54- maxPromptLength?: "none" | 1024 | 4096
52+ firstMessage?: string
5553 ) => Promise<number | null>,
5654 onThreadSelect: (id: number) => void,
5755 onThreadsReload: () => void,
@@ -66,12 +64,10 @@ export function useMessages(
6664
6765 if (!targetThreadId) {
6866 // Create a new thread if none exists
69- // Use the validated selectedModel instead of reading from localStorage
67+ // The onCreateThread callback should already have model and maxPromptLength
7068 targetThreadId = await onCreateThread(
7169 message.substring(0, 100),
72- message,
73- selectedModel,
74- maxPromptLength
70+ message
7571 );
7672 if (!targetThreadId) {
7773 setIsLoading(false);
src/hooks/useSettings.ts+3−103
@@ -1,13 +1,11 @@
11 import { useState, useEffect } from "react";
22
33 export function useSettings(onError?: (error: string) => void) {
4- const [selectedModel, setSelectedModel] = useState<string>("gpt-oss");
5- const [maxPromptLength, setMaxPromptLength] = useState<"none" | 1024 | 4096>("none");
64 const [location, setLocation] = useState<string>("");
75
8- // Load settings from API and validate model against available models
6+ // Load settings from API
97 useEffect(() => {
10- const loadAndValidateSettings = async () => {
8+ const loadSettings = async () => {
119 try {
1210 // Load saved settings from API
1311 const settingsRes = await fetch("/api/settings");
@@ -21,26 +19,8 @@ export function useSettings(onError?: (error: string) => void) {
2119 }
2220 const settingsData = await settingsRes.json();
2321 const settings = settingsData.settings || {};
24- const savedModel = settings.selectedModel || "";
25- const savedMaxPromptLength = settings.maxPromptLength || "none";
2622 const savedLocation = settings.location || "";
2723
28- // Get available models
29- const modelsRes = await fetch("/api/models");
30- if (!modelsRes.ok) {
31- const errorData = await modelsRes.json().catch((parseError) => {
32- throw new Error(
33- `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
34- );
35- });
36- throw new Error(errorData.error || modelsRes.statusText);
37- }
38- const modelsData = await modelsRes.json();
39- const availableModels = modelsData.models || [];
40-
41- // Set maxPromptLength
42- setMaxPromptLength(savedMaxPromptLength);
43-
4424 // Get browser timezone and post current time in ISO format to settings on app start
4525 const browserTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
4626 const currentTimeISO = new Date().toISOString();
@@ -65,94 +45,18 @@ export function useSettings(onError?: (error: string) => void) {
6545 onError(error.message);
6646 }
6747 }
68-
69- if (availableModels.length === 0) {
70- // No models available, keep default
71- setSelectedModel("gpt-oss");
72- return;
73- }
74-
75- // Check if saved model exists in available models
76- const modelExists = availableModels.some(
77- (m: { name: string; model: string }) => m.model === savedModel
78- );
79-
80- if (modelExists) {
81- // Model is valid, use it
82- setSelectedModel(savedModel);
83- } else {
84- // Model doesn't exist, fall back to first available model
85- const fallbackModel = availableModels[0].model;
86- setSelectedModel(fallbackModel);
87- // Save fallback to API
88- await fetch("/api/settings", {
89- method: "POST",
90- headers: { "Content-Type": "application/json" },
91- body: JSON.stringify({ selectedModel: fallbackModel }),
92- });
93- }
9448 } catch (error) {
9549 if (onError && error instanceof Error) {
9650 onError(error.message);
9751 }
9852 // On error, keep defaults
99- setSelectedModel("");
100- setMaxPromptLength("none");
10153 setLocation("");
10254 }
10355 };
10456
105- loadAndValidateSettings();
57+ loadSettings();
10658 }, [onError]);
10759
108- const handleModelChange = async (model: string) => {
109- setSelectedModel(model);
110- // Save to API
111- try {
112- const res = await fetch("/api/settings", {
113- method: "POST",
114- headers: { "Content-Type": "application/json" },
115- body: JSON.stringify({ selectedModel: model }),
116- });
117- if (!res.ok) {
118- const errorData = await res.json().catch((parseError) => {
119- throw new Error(
120- `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
121- );
122- });
123- throw new Error(errorData.error || res.statusText);
124- }
125- } catch (error) {
126- if (onError && error instanceof Error) {
127- onError(error.message);
128- }
129- }
130- };
131-
132- const handleMaxPromptLengthChange = async (value: "none" | 1024 | 4096) => {
133- setMaxPromptLength(value);
134- // Save to API
135- try {
136- const res = await fetch("/api/settings", {
137- method: "POST",
138- headers: { "Content-Type": "application/json" },
139- body: JSON.stringify({ maxPromptLength: value }),
140- });
141- if (!res.ok) {
142- const errorData = await res.json().catch((parseError) => {
143- throw new Error(
144- `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
145- );
146- });
147- throw new Error(errorData.error || res.statusText);
148- }
149- } catch (error) {
150- if (onError && error instanceof Error) {
151- onError(error.message);
152- }
153- }
154- };
155-
15660 const handleLocationChange = async (value: string) => {
15761 setLocation(value);
15862 // Save to API
@@ -178,10 +82,6 @@ export function useSettings(onError?: (error: string) => void) {
17882 };
17983
18084 return {
181- selectedModel,
182- handleModelChange,
183- maxPromptLength,
184- handleMaxPromptLengthChange,
18585 location,
18686 handleLocationChange,
18787 };
src/hooks/useThreads.ts+4−20
@@ -49,36 +49,20 @@ export function useThreads() {
4949 const createThread = async (
5050 titleOverride?: string,
5151 firstMessage?: string,
52- model?: string,
53- maxPromptLength?: "none" | 1024 | 4096,
52+ model: string,
53+ maxPromptLength: "none" | 1024 | 4096,
5454 onError?: (error: string) => void
5555 ): Promise<number | null> => {
5656 try {
5757 const title = titleOverride || (firstMessage ? firstMessage.substring(0, 100) : "New Thread");
58- // Use global model setting (from localStorage) when creating a new thread
59- // This will be stored in the thread table and used for all messages in this thread
60- const modelToUse = model || localStorage.getItem("selectedModel") || "gpt-oss";
61-
62- // Get maxPromptLength from global settings if not provided
63- // This will be stored in the thread table and used for all messages in this thread
64- let maxPromptLengthToUse = maxPromptLength;
65- if (maxPromptLengthToUse === undefined) {
66- try {
67- const settingsRes = await fetch("/api/settings");
68- const settingsData = await settingsRes.json();
69- maxPromptLengthToUse = settingsData.settings?.maxPromptLength || "none";
70- } catch {
71- maxPromptLengthToUse = "none";
72- }
73- }
7458
7559 const res = await fetch("/api/threads", {
7660 method: "POST",
7761 headers: { "Content-Type": "application/json" },
7862 body: JSON.stringify({
7963 title,
80- model: modelToUse,
81- maxPromptLength: maxPromptLengthToUse,
64+ model,
65+ maxPromptLength,
8266 }),
8367 });
8468 if (!res.ok) {