xonecas.io
53129
Pa

PAT / commit 08425e6

fix: second attempt and implemnting user context

xonecas2025-12-19 08425e609a3abec8c3fcfacfb259bb6900a87bd1 parent 65643c8

24 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

TODO.md+7−0
@@ -9,3 +9,10 @@
99 - Sidebar improvements, more information about the thread quickly
1010 - Text input, we should be able to press a button and record a prompt.
1111 - Text to voice, we should have a button to have the models replies be read with text to voice.
12+
13+# new thread setting: User Prompt
14+
15+- Add a new thread setting called user prompt, a string, this setting should be persisted in the threads table and default to null
16+- Update the system prompt generation to include the user prompt if it is not null
17+
18+Extract the system prompt generation from the route file into it's own file in lib/ollama/system-prompt
app/api/chat/route.ts+0−1
@@ -53,7 +53,6 @@ export async function POST(request: Request) {
5353 });
5454
5555 // 4. Build messages array for Ollama
56- // Note: tool_calls are not needed for conversation history, only stored for display
5756 const ollamaMessages: Message[] = previousMessages.map((msg) => ({
5857 role: msg.role as Message["role"],
5958 content: msg.content,
app/api/settings/route.ts+0−70
@@ -1,70 +0,0 @@
1-import { NextResponse } from "next/server";
2-import { getCache, setCache } from "@/src/lib/cache";
3-
4-const SETTINGS_CACHE_KEY = "app_settings";
5-
6-type Settings = {
7- location?: string;
8- currentTime?: string;
9- timezone?: string;
10-};
11-
12-export async function GET() {
13- try {
14- const settings = await getCache<Settings>(SETTINGS_CACHE_KEY);
15- if (settings) {
16- return NextResponse.json({ settings });
17- }
18-
19- const defaultSettings: Settings = {};
20-
21- return NextResponse.json({ settings: defaultSettings });
22- } catch {
23- return NextResponse.json({ error: "Failed to get settings" }, { status: 500 });
24- }
25-}
26-
27-export async function POST(request: Request) {
28- try {
29- const { location, currentTime, timezone } = await request.json();
30-
31- let settings: Partial<Settings> = {};
32-
33- // Validate and set location if provided
34- if (location !== undefined) {
35- if (typeof location !== "string") {
36- return NextResponse.json({ error: "Invalid location value" }, { status: 400 });
37- }
38- settings.location = location;
39- }
40-
41- // Validate and set currentTime if provided
42- if (currentTime !== undefined) {
43- if (typeof currentTime !== "string") {
44- return NextResponse.json({ error: "Invalid currentTime value" }, { status: 400 });
45- }
46- settings.currentTime = currentTime;
47- }
48-
49- // Validate and set timezone if provided
50- if (timezone !== undefined) {
51- if (typeof timezone !== "string") {
52- return NextResponse.json({ error: "Invalid timezone value" }, { status: 400 });
53- }
54- settings.timezone = timezone;
55- }
56-
57- // Get existing settings and merge, prefering the ones in the request
58- const existingSettings = await getCache<Settings>(SETTINGS_CACHE_KEY);
59- if (existingSettings) {
60- settings = { ...existingSettings, ...settings };
61- }
62-
63- // Update the cache with new settings.
64- await setCache(SETTINGS_CACHE_KEY, settings);
65-
66- return NextResponse.json({ settings: settings });
67- } catch {
68- return NextResponse.json({ error: "Failed to set settings" }, { status: 500 });
69- }
70-}
app/api/threads/[id]/route.ts+9−1
@@ -12,7 +12,15 @@ export async function PATCH(request: Request, { params }: { params: Promise<{ id
1212 }
1313
1414 const body = await request.json();
15- const { model, maxPromptLength, title } = body;
15+ const { model, maxPromptLength, title, userPrompt } = body;
16+
17+ // Reject userPrompt updates - it can only be set at thread creation
18+ if (userPrompt !== undefined) {
19+ return NextResponse.json(
20+ { error: "User prompt can only be set when creating a new thread" },
21+ { status: 400 }
22+ );
23+ }
1624
1725 const updateData: {
1826 model?: string;
app/api/threads/route.ts+11−53
@@ -2,20 +2,12 @@ import { NextResponse } from "next/server";
22 import { db } from "@/src/lib/db";
33 import { threads, messages } from "@/src/lib/db/schema";
44 import { desc, count } from "drizzle-orm";
5-import { getCache } from "@/src/lib/cache";
6-
7-const SETTINGS_CACHE_KEY = "app_settings";
8-
9-type Settings = {
10- location?: string;
11- currentTime?: string;
12- timezone?: string;
13-};
5+import { generateSystemPrompt } from "@/src/lib/ollama/chat/system-prompt";
146
157 export async function POST(request: Request) {
168 try {
17- const { title, model, maxPromptLength } = await request.json();
18-
9+ const { title, model, maxPromptLength, userPrompt, time, timezone } = await request.json();
10+
1911 // Validate required parameters
2012 if (!model || typeof model !== "string") {
2113 return NextResponse.json({ error: "model is required" }, { status: 400 });
@@ -23,7 +15,7 @@ export async function POST(request: Request) {
2315 if (maxPromptLength === undefined) {
2416 return NextResponse.json({ error: "maxPromptLength is required" }, { status: 400 });
2517 }
26-
18+
2719 const newThread = await db
2820 .insert(threads)
2921 .values({
@@ -31,6 +23,7 @@ export async function POST(request: Request) {
3123 model: model,
3224 maxPromptLength:
3325 maxPromptLength === "none" || maxPromptLength === null ? null : maxPromptLength,
26+ userPrompt: userPrompt || null,
3427 createdAt: new Date(),
3528 updatedAt: new Date(),
3629 })
@@ -38,47 +31,12 @@ export async function POST(request: Request) {
3831
3932 const threadId = newThread[0].id;
4033
41- // Get location, currentTime, and timezone from settings
42- const settings = await getCache<Settings>(SETTINGS_CACHE_KEY);
43- const location = settings?.location;
44- const currentTime = settings?.currentTime;
45- const timezone = settings?.timezone;
46-
47- // Build system prompt with location and time if available
48- let systemPrompt = `You are PAT, a helpful personal assistant. You must follow these guidelines:
49-- Only repeat tool calls in case of errors
50-- Use simple and concise language
51-- Reply with markdown whenever possible
52-- When asked for code or text return it in a markdown code block`;
53-
54- if (location || currentTime || timezone) {
55- systemPrompt += "\n\n";
56- if (currentTime && timezone) {
57- // Format time in the user's timezone
58- try {
59- const timeDate = new Date(currentTime);
60- const formattedTime = new Intl.DateTimeFormat("en-US", {
61- timeZone: timezone,
62- year: "numeric",
63- month: "long",
64- day: "numeric",
65- hour: "numeric",
66- minute: "2-digit",
67- second: "2-digit",
68- timeZoneName: "short",
69- }).format(timeDate);
70- systemPrompt += `Current time: ${formattedTime}\n`;
71- } catch (error) {
72- // Fallback to ISO string if timezone formatting fails
73- systemPrompt += `Current time: ${currentTime}\n`;
74- }
75- } else if (currentTime) {
76- systemPrompt += `Current time: ${currentTime}\n`;
77- }
78- if (location) {
79- systemPrompt += `Location: ${location}`;
80- }
81- }
34+ // Generate system prompt
35+ const systemPrompt = generateSystemPrompt({
36+ time,
37+ timezone,
38+ userPrompt: userPrompt || null,
39+ });
8240
8341 // Insert system message with guidelines
8442 await db.insert(messages).values({
app/page.tsx+40−23
@@ -5,18 +5,24 @@ import MessageInput, { type MessageInputRef } from "@/src/components/MessageInpu
55 import MessageList from "@/src/components/MessageList";
66 import NoThreadSelected from "@/src/components/NoThreadSelected";
77 import { useTheme } from "@/src/hooks/useTheme";
8-import { useSettings } from "@/src/hooks/useSettings";
98 import { useThreads } from "@/src/hooks/useThreads";
109 import { useMessages } from "@/src/hooks/useMessages";
1110 import { useThreadSelection } from "@/src/hooks/useThreadSelection";
11+import { useLocalStorage } from "@/src/hooks/useLocalStorage";
1212 import "./highlight-theme.css";
1313
1414 export default function Home() {
1515 const [error, setError] = useState<string | null>(null);
1616 const { themeMode, handleThemeChange } = useTheme();
17- const { location, handleLocationChange } = useSettings(setError);
18- const [selectedModel, setSelectedModel] = useState<string>("gpt-oss");
19- const [maxPromptLength, setMaxPromptLength] = useState<"none" | 1024 | 4096>("none");
17+ const [selectedModel, setSelectedModel] = useLocalStorage<string>("selectedModel", "gpt-oss");
18+ const [maxPromptLength, setMaxPromptLength] = useLocalStorage<"none" | 1024 | 4096>(
19+ "maxPromptLength",
20+ "none"
21+ );
22+ const [newThreadUserPrompt, setNewThreadUserPrompt] = useLocalStorage<string>(
23+ "newThreadUserPrompt",
24+ ""
25+ );
2026 const {
2127 threads,
2228 totalThreadCount,
@@ -44,23 +50,22 @@ export default function Home() {
4450 });
4551 const messageInputRef = useRef<MessageInputRef>(null);
4652
47- // Initialize model from localStorage or fetch first available model
53+ // Validate and initialize model from localStorage or fetch first available model
4854 useEffect(() => {
4955 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
56+ // Capture the current selectedModel value
57+ const currentModel = selectedModel;
58+ // Validate that the saved model still exists
59+ if (currentModel) {
5460 try {
5561 const res = await fetch("/api/models");
5662 if (res.ok) {
5763 const data = await res.json();
5864 const availableModels = data.models || [];
5965 const modelExists = availableModels.some(
60- (m: { name: string; model: string }) => m.model === savedModel
66+ (m: { name: string; model: string }) => m.model === currentModel
6167 );
6268 if (modelExists) {
63- setSelectedModel(savedModel);
6469 return;
6570 }
6671 }
@@ -68,7 +73,7 @@ export default function Home() {
6873 // Fall through to default
6974 }
7075 }
71-
76+
7277 // If no saved model or it doesn't exist, get first available
7378 try {
7479 const res = await fetch("/api/models");
@@ -78,26 +83,28 @@ export default function Home() {
7883 if (availableModels.length > 0) {
7984 const firstModel = availableModels[0].model;
8085 setSelectedModel(firstModel);
81- localStorage.setItem("selectedModel", firstModel);
8286 }
8387 }
8488 } catch {
8589 // Keep default
8690 }
8791 };
88-
92+
8993 initializeModel();
90- }, []);
94+ }, [selectedModel, setSelectedModel]);
9195
9296 const handleModelChange = (model: string) => {
9397 setSelectedModel(model);
94- localStorage.setItem("selectedModel", model);
9598 };
9699
97100 const handleMaxPromptLengthChange = (value: "none" | 1024 | 4096) => {
98101 setMaxPromptLength(value);
99102 };
100103
104+ const handleNewThreadUserPromptChange = (userPrompt: string) => {
105+ setNewThreadUserPrompt(userPrompt);
106+ };
107+
101108 const handleDeleteMessage = (messageId: number, threadId: number) => {
102109 deleteMessageInternal(messageId, threadId, setError);
103110 };
@@ -129,7 +136,11 @@ export default function Home() {
129136
130137 const handleThreadUpdate = async (
131138 threadId: number,
132- updates: { model?: string; maxPromptLength?: "none" | 1024 | 4096 | null }
139+ updates: {
140+ model?: string;
141+ maxPromptLength?: "none" | 1024 | 4096 | null;
142+ userPrompt?: string | null;
143+ }
133144 ) => {
134145 setError(null);
135146 try {
@@ -166,11 +177,16 @@ export default function Home() {
166177 message,
167178 currentThreadId,
168179 (title, firstMessage) =>
169- createThread(title, firstMessage, selectedModel, maxPromptLength, setError),
180+ createThread(
181+ selectedModel,
182+ maxPromptLength,
183+ title,
184+ firstMessage,
185+ newThreadUserPrompt,
186+ setError
187+ ),
170188 selectThread,
171189 () => loadThreads(8, setError),
172- selectedModel,
173- maxPromptLength,
174190 setError
175191 );
176192 } catch (error) {
@@ -193,7 +209,7 @@ export default function Home() {
193209 className={`mx-auto flex min-h-full max-w-5xl flex-col gap-8 ${currentThreadId === null ? "justify-center" : "justify-end"}`}
194210 >
195211 {currentThreadId === null ? (
196- <NoThreadSelected threadCount={totalThreadCount} />
212+ <NoThreadSelected />
197213 ) : (
198214 <MessageList
199215 messages={messages}
@@ -221,8 +237,10 @@ export default function Home() {
221237 onError={setError}
222238 newThreadModel={selectedModel}
223239 newThreadMaxPromptLength={maxPromptLength}
240+ newThreadUserPrompt={newThreadUserPrompt}
224241 onNewThreadModelChange={handleModelChange}
225242 onNewThreadMaxPromptLengthChange={handleMaxPromptLengthChange}
243+ onNewThreadUserPromptChange={handleNewThreadUserPromptChange}
226244 />
227245 </div>
228246 <Sidebar
@@ -236,8 +254,7 @@ export default function Home() {
236254 void loadMoreThreads(8, setError);
237255 }}
238256 hasMoreThreads={hasMoreThreads}
239- location={location}
240- onLocationChange={handleLocationChange}
257+ totalThreadCount={totalThreadCount}
241258 />
242259 </div>
243260 );
drizzle/0006_productive_smasher.sql+1−0
@@ -0,0 +1 @@
1+ALTER TABLE "threads" ADD COLUMN "user_prompt" text;
drizzle/meta/0006_snapshot.json+159−0
@@ -0,0 +1,159 @@
1+{
2+ "id": "58baed47-8a10-4003-81cf-3cc9854ac3cb",
3+ "prevId": "c986ec80-6630-4a52-97f2-3df6e02ca96b",
4+ "version": "7",
5+ "dialect": "postgresql",
6+ "tables": {
7+ "public.messages": {
8+ "name": "messages",
9+ "schema": "",
10+ "columns": {
11+ "id": {
12+ "name": "id",
13+ "type": "serial",
14+ "primaryKey": true,
15+ "notNull": true
16+ },
17+ "thread_id": {
18+ "name": "thread_id",
19+ "type": "integer",
20+ "primaryKey": false,
21+ "notNull": true
22+ },
23+ "role": {
24+ "name": "role",
25+ "type": "text",
26+ "primaryKey": false,
27+ "notNull": true
28+ },
29+ "content": {
30+ "name": "content",
31+ "type": "text",
32+ "primaryKey": false,
33+ "notNull": true
34+ },
35+ "model": {
36+ "name": "model",
37+ "type": "text",
38+ "primaryKey": false,
39+ "notNull": false
40+ },
41+ "max_prompt_length": {
42+ "name": "max_prompt_length",
43+ "type": "integer",
44+ "primaryKey": false,
45+ "notNull": false
46+ },
47+ "created_at": {
48+ "name": "created_at",
49+ "type": "timestamp with time zone",
50+ "primaryKey": false,
51+ "notNull": true,
52+ "default": "now()"
53+ },
54+ "generation_time_ms": {
55+ "name": "generation_time_ms",
56+ "type": "integer",
57+ "primaryKey": false,
58+ "notNull": false
59+ },
60+ "tool_call_counts": {
61+ "name": "tool_call_counts",
62+ "type": "text",
63+ "primaryKey": false,
64+ "notNull": false
65+ }
66+ },
67+ "indexes": {},
68+ "foreignKeys": {
69+ "messages_thread_id_threads_id_fk": {
70+ "name": "messages_thread_id_threads_id_fk",
71+ "tableFrom": "messages",
72+ "tableTo": "threads",
73+ "columnsFrom": [
74+ "thread_id"
75+ ],
76+ "columnsTo": [
77+ "id"
78+ ],
79+ "onDelete": "cascade",
80+ "onUpdate": "no action"
81+ }
82+ },
83+ "compositePrimaryKeys": {},
84+ "uniqueConstraints": {},
85+ "policies": {},
86+ "checkConstraints": {},
87+ "isRLSEnabled": false
88+ },
89+ "public.threads": {
90+ "name": "threads",
91+ "schema": "",
92+ "columns": {
93+ "id": {
94+ "name": "id",
95+ "type": "serial",
96+ "primaryKey": true,
97+ "notNull": true
98+ },
99+ "title": {
100+ "name": "title",
101+ "type": "text",
102+ "primaryKey": false,
103+ "notNull": false
104+ },
105+ "model": {
106+ "name": "model",
107+ "type": "text",
108+ "primaryKey": false,
109+ "notNull": true,
110+ "default": "'gpt-oss'"
111+ },
112+ "max_prompt_length": {
113+ "name": "max_prompt_length",
114+ "type": "integer",
115+ "primaryKey": false,
116+ "notNull": false
117+ },
118+ "user_prompt": {
119+ "name": "user_prompt",
120+ "type": "text",
121+ "primaryKey": false,
122+ "notNull": false
123+ },
124+ "created_at": {
125+ "name": "created_at",
126+ "type": "timestamp with time zone",
127+ "primaryKey": false,
128+ "notNull": true,
129+ "default": "now()"
130+ },
131+ "updated_at": {
132+ "name": "updated_at",
133+ "type": "timestamp with time zone",
134+ "primaryKey": false,
135+ "notNull": true,
136+ "default": "now()"
137+ }
138+ },
139+ "indexes": {},
140+ "foreignKeys": {},
141+ "compositePrimaryKeys": {},
142+ "uniqueConstraints": {},
143+ "policies": {},
144+ "checkConstraints": {},
145+ "isRLSEnabled": false
146+ }
147+ },
148+ "enums": {},
149+ "schemas": {},
150+ "sequences": {},
151+ "roles": {},
152+ "policies": {},
153+ "views": {},
154+ "_meta": {
155+ "columns": {},
156+ "schemas": {},
157+ "tables": {}
158+ }
159+}
drizzle/meta/_journal.json+7−0
@@ -43,6 +43,13 @@
4343 "when": 1766093474935,
4444 "tag": "0005_harsh_wild_pack",
4545 "breakpoints": true
46+ },
47+ {
48+ "idx": 6,
49+ "version": "7",
50+ "when": 1766148194532,
51+ "tag": "0006_productive_smasher",
52+ "breakpoints": true
4653 }
4754 ]
4855 }
src/components/MessageInput.tsx+15−2
@@ -21,14 +21,20 @@ type MessageInputProps = {
2121 currentThread: Thread | null;
2222 onThreadUpdate?: (
2323 threadId: number,
24- updates: { model?: string; maxPromptLength?: "none" | 1024 | 4096 | null }
24+ updates: {
25+ model?: string;
26+ maxPromptLength?: "none" | 1024 | 4096 | null;
27+ userPrompt?: string | null;
28+ }
2529 ) => Promise<void>;
2630 onThreadDelete?: (threadId: number) => Promise<void>;
2731 onError?: (error: string) => void;
2832 newThreadModel?: string;
2933 newThreadMaxPromptLength?: "none" | 1024 | 4096;
34+ newThreadUserPrompt?: string;
3035 onNewThreadModelChange?: (model: string) => void;
3136 onNewThreadMaxPromptLengthChange?: (value: "none" | 1024 | 4096) => void;
37+ onNewThreadUserPromptChange?: (userPrompt: string) => void;
3238 };
3339
3440 export type MessageInputRef = {
@@ -52,8 +58,10 @@ const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
5258 onError,
5359 newThreadModel,
5460 newThreadMaxPromptLength,
61+ newThreadUserPrompt,
5562 onNewThreadModelChange,
5663 onNewThreadMaxPromptLengthChange,
64+ onNewThreadUserPromptChange,
5765 },
5866 ref
5967 ) => {
@@ -168,13 +176,18 @@ const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
168176 onDeleteThread={onThreadDelete}
169177 onError={onError}
170178 />
171- ) : currentThreadId === null && onNewThreadModelChange && onNewThreadMaxPromptLengthChange ? (
179+ ) : currentThreadId === null &&
180+ onNewThreadModelChange &&
181+ onNewThreadMaxPromptLengthChange &&
182+ onNewThreadUserPromptChange ? (
172183 <ThreadSettingsButton
173184 thread={null}
174185 initialModel={newThreadModel}
175186 initialMaxPromptLength={newThreadMaxPromptLength}
187+ initialUserPrompt={newThreadUserPrompt}
176188 onModelChange={onNewThreadModelChange}
177189 onMaxPromptLengthChange={onNewThreadMaxPromptLengthChange}
190+ onUserPromptChange={onNewThreadUserPromptChange}
178191 onError={onError}
179192 />
180193 ) : null}
src/components/NoThreadSelected.tsx+1−39
@@ -1,32 +1,6 @@
11 "use client";
22
3-import { useState, useEffect } from "react";
4-
5-type NoThreadSelectedProps = {
6- threadCount: number;
7-};
8-
9-export default function NoThreadSelected({
10- threadCount,
11-}: NoThreadSelectedProps) {
12- const [currentTime, setCurrentTime] = useState<Date | null>(null);
13-
14- useEffect(() => {
15- // Set initial time only on client after hydration
16- setCurrentTime(new Date());
17- const timer = setInterval(() => {
18- setCurrentTime(new Date());
19- }, 1000);
20-
21- return () => clearInterval(timer);
22- }, []);
23-
24- const formatTime = (date: Date): string => {
25- return date.toLocaleString();
26- };
27-
28- const timeDisplay = currentTime ? formatTime(currentTime) : "";
29-
3+export default function NoThreadSelected() {
304 return (
315 <div className="mx-auto min-w-0 max-w-5xl">
326 <div className="flex flex-col gap-4 bg-neutral-200 p-8 dark:bg-neutral-900">
@@ -36,18 +10,6 @@ export default function NoThreadSelected({
3610 below to start new a conversation thread or pick a previous conversation thread from the
3711 sidebar.
3812 </p>
39- <hr className="border-neutral-300 dark:border-neutral-700" />
40- <p className="text-sm text-neutral-600 dark:text-neutral-400">
41- {timeDisplay && (
42- <>
43- <em>Current time: {timeDisplay}</em>
44- <br />
45- </>
46- )}
47- <em>
48- {threadCount} {threadCount === 1 ? "thread" : "threads"} created
49- </em>
50- </p>
5113 </div>
5214 </div>
5315 );
src/components/SettingsModal.tsx+0−14
@@ -7,8 +7,6 @@ type SettingsModalProps = {
77 onClose: () => void;
88 themeMode: "device" | "dark" | "light";
99 onThemeChange: (mode: "device" | "dark" | "light") => void;
10- location: string;
11- onLocationChange: (location: string) => void;
1210 };
1311
1412 export default function SettingsModal({
@@ -16,8 +14,6 @@ export default function SettingsModal({
1614 onClose,
1715 themeMode,
1816 onThemeChange,
19- location,
20- onLocationChange,
2117 }: SettingsModalProps) {
2218 return (
2319 <Modal isOpen={isOpen} onClose={onClose}>
@@ -37,16 +33,6 @@ export default function SettingsModal({
3733 <option value="light">Light</option>
3834 </select>
3935 </div>
40- <div className="flex flex-col gap-2">
41- <label className="text-neutral-600 dark:text-neutral-400">Location</label>
42- <input
43- type="text"
44- value={location}
45- onChange={(e) => onLocationChange(e.target.value)}
46- placeholder="Enter location name (e.g., New York, London)"
47- className="bg-white px-3 py-1 text-neutral-800 focus:outline-none dark:bg-neutral-950 dark:text-neutral-200"
48- />
49- </div>
5036 </div>
5137 </Modal>
5238 );
src/components/Sidebar.tsx+8−7
@@ -18,8 +18,7 @@ type SidebarProps = {
1818 onThemeChange: (mode: "device" | "dark" | "light") => void;
1919 onLoadMore: () => void;
2020 hasMoreThreads: boolean;
21- location: string;
22- onLocationChange: (location: string) => void;
21+ totalThreadCount: number;
2322 };
2423
2524 export default function Sidebar({
@@ -31,8 +30,7 @@ export default function Sidebar({
3130 onThemeChange,
3231 onLoadMore,
3332 hasMoreThreads,
34- location,
35- onLocationChange,
33+ totalThreadCount,
3634 }: SidebarProps) {
3735 const [isSettingsOpen, setIsSettingsOpen] = useState(false);
3836
@@ -64,7 +62,12 @@ export default function Sidebar({
6462 <GearIcon className="h-4 w-4" />
6563 Settings
6664 </SecondaryButton>
67- <label className="text-neutral-500">Threads</label>
65+ <label className="text-neutral-500">
66+ Threads{" "}
67+ <span className="text-neutral-400 dark:text-neutral-500">
68+ ({threads.length} out of {totalThreadCount})
69+ </span>
70+ </label>
6871 <div className="flex flex-col gap-2">
6972 <div className="flex flex-col">
7073 {threads.length === 0 ? (
@@ -115,8 +118,6 @@ export default function Sidebar({
115118 onClose={() => setIsSettingsOpen(false)}
116119 themeMode={themeMode}
117120 onThemeChange={onThemeChange}
118- location={location}
119- onLocationChange={onLocationChange}
120121 />
121122 </>
122123 );
src/components/ThreadSettingsButton.tsx+11−1
@@ -9,14 +9,20 @@ type ThreadSettingsButtonProps = {
99 thread: Thread | null;
1010 onUpdateThread?: (
1111 threadId: number,
12- updates: { model?: string; maxPromptLength?: "none" | 1024 | 4096 | null }
12+ updates: {
13+ model?: string;
14+ maxPromptLength?: "none" | 1024 | 4096 | null;
15+ userPrompt?: string | null;
16+ }
1317 ) => Promise<void>;
1418 onDeleteThread?: (threadId: number) => Promise<void>;
1519 onError?: (error: string) => void;
1620 initialModel?: string;
1721 initialMaxPromptLength?: "none" | 1024 | 4096;
22+ initialUserPrompt?: string;
1823 onModelChange?: (model: string) => void;
1924 onMaxPromptLengthChange?: (value: "none" | 1024 | 4096) => void;
25+ onUserPromptChange?: (userPrompt: string) => void;
2026 };
2127
2228 export default function ThreadSettingsButton({
@@ -26,8 +32,10 @@ export default function ThreadSettingsButton({
2632 onError,
2733 initialModel,
2834 initialMaxPromptLength,
35+ initialUserPrompt,
2936 onModelChange,
3037 onMaxPromptLengthChange,
38+ onUserPromptChange,
3139 }: ThreadSettingsButtonProps) {
3240 const [isModalOpen, setIsModalOpen] = useState(false);
3341
@@ -54,8 +62,10 @@ export default function ThreadSettingsButton({
5462 onError={onError}
5563 initialModel={initialModel}
5664 initialMaxPromptLength={initialMaxPromptLength}
65+ initialUserPrompt={initialUserPrompt}
5766 onModelChange={onModelChange}
5867 onMaxPromptLengthChange={onMaxPromptLengthChange}
68+ onUserPromptChange={onUserPromptChange}
5969 />
6070 </>
6171 );
src/components/ThreadSettingsModal.tsx+37−4
@@ -3,7 +3,6 @@
33 import { useState, useEffect } from "react";
44 import Modal from "@/src/components/Modal";
55 import SecondaryButton from "@/src/components/buttons/SecondaryButton";
6-import PrimaryButton from "@/src/components/buttons/PrimaryButton";
76 import TrashIcon from "@/src/components/icons/TrashIcon";
87 import type { Thread } from "@/src/lib/db/schema";
98
@@ -13,14 +12,20 @@ type ThreadSettingsModalProps = {
1312 thread: Thread | null;
1413 onUpdateThread?: (
1514 threadId: number,
16- updates: { model?: string; maxPromptLength?: "none" | 1024 | 4096 | null }
15+ updates: {
16+ model?: string;
17+ maxPromptLength?: "none" | 1024 | 4096 | null;
18+ userPrompt?: string | null;
19+ }
1720 ) => Promise<void>;
1821 onDeleteThread?: (threadId: number) => Promise<void>;
1922 onError?: (error: string) => void;
2023 initialModel?: string;
2124 initialMaxPromptLength?: "none" | 1024 | 4096;
25+ initialUserPrompt?: string;
2226 onModelChange?: (model: string) => void;
2327 onMaxPromptLengthChange?: (value: "none" | 1024 | 4096) => void;
28+ onUserPromptChange?: (userPrompt: string) => void;
2429 };
2530
2631 export default function ThreadSettingsModal({
@@ -32,13 +37,16 @@ export default function ThreadSettingsModal({
3237 onError,
3338 initialModel,
3439 initialMaxPromptLength,
40+ initialUserPrompt,
3541 onModelChange,
3642 onMaxPromptLengthChange,
43+ onUserPromptChange,
3744 }: ThreadSettingsModalProps) {
3845 const [models, setModels] = useState<Array<{ name: string; model: string }>>([]);
3946 const [isLoadingModels, setIsLoadingModels] = useState(false);
4047 const [selectedModel, setSelectedModel] = useState<string>("gpt-oss");
4148 const [maxPromptLength, setMaxPromptLength] = useState<"none" | 1024 | 4096 | null>("none");
49+ const [userPrompt, setUserPrompt] = useState<string>("");
4250 const [isSaving, setIsSaving] = useState(false);
4351 const [isDeleting, setIsDeleting] = useState(false);
4452 const isNewThread = thread === null;
@@ -80,12 +88,14 @@ export default function ThreadSettingsModal({
8088 setMaxPromptLength(
8189 thread.maxPromptLength === null ? "none" : (thread.maxPromptLength as 1024 | 4096)
8290 );
91+ setUserPrompt(thread.userPrompt || "");
8392 } else if (isOpen && isNewThread) {
8493 // For new thread, use initial values or defaults
8594 setSelectedModel(initialModel || "gpt-oss");
8695 setMaxPromptLength(initialMaxPromptLength || "none");
96+ setUserPrompt(initialUserPrompt || "");
8797 }
88- }, [thread, isOpen, isNewThread, initialModel, initialMaxPromptLength]);
98+ }, [thread, isOpen, isNewThread, initialModel, initialMaxPromptLength, initialUserPrompt]);
8999
90100 const handleSave = async () => {
91101 if (isNewThread) {
@@ -96,6 +106,9 @@ export default function ThreadSettingsModal({
96106 if (onMaxPromptLengthChange && maxPromptLength !== null) {
97107 onMaxPromptLengthChange(maxPromptLength === "none" ? "none" : maxPromptLength);
98108 }
109+ if (onUserPromptChange) {
110+ onUserPromptChange(userPrompt);
111+ }
99112 onClose();
100113 return;
101114 }
@@ -115,6 +128,7 @@ export default function ThreadSettingsModal({
115128
116129 setIsSaving(true);
117130 try {
131+ // Don't send userPrompt for existing threads - it's read-only
118132 await onUpdateThread(thread.id, {
119133 model: selectedModel,
120134 maxPromptLength: maxPromptLength === "none" ? null : maxPromptLength,
@@ -145,7 +159,7 @@ export default function ThreadSettingsModal({
145159 }
146160 };
147161
148- const threadTitle = thread ? (thread.title || `Thread ${thread.id}`) : null;
162+ const threadTitle = thread ? thread.title || `Thread ${thread.id}` : null;
149163
150164 return (
151165 <Modal isOpen={isOpen} onClose={onClose}>
@@ -200,6 +214,25 @@ export default function ThreadSettingsModal({
200214 <option value="4096">4096</option>
201215 </select>
202216 </div>
217+
218+ <div className="flex flex-col gap-2">
219+ <label className="text-sm font-medium text-neutral-600 dark:text-neutral-400">
220+ User Prompt
221+ </label>
222+ <textarea
223+ value={userPrompt}
224+ onChange={(e) => setUserPrompt(e.target.value)}
225+ placeholder="Additional instructions or information for the assistant..."
226+ rows={4}
227+ disabled={!isNewThread}
228+ 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"
229+ />
230+ {!isNewThread && (
231+ <p className="text-xs text-neutral-500 dark:text-neutral-500">
232+ User prompt can only be set when creating a new thread.
233+ </p>
234+ )}
235+ </div>
203236 </div>
204237
205238 <div className="flex justify-between gap-2 border-t border-neutral-300 pt-4 dark:border-neutral-700">
src/hooks/useLocalStorage.ts+53−0
@@ -0,0 +1,53 @@
1+import { useState } from "react";
2+
3+/**
4+ * Custom hook for managing localStorage with React state
5+ * @param key - The localStorage key
6+ * @param initialValue - The initial value if no value exists in localStorage
7+ * @returns A tuple of [value, setValue] similar to useState
8+ */
9+export function useLocalStorage<T>(
10+ key: string,
11+ initialValue: T
12+): [T, (value: T | ((prev: T) => T)) => void] {
13+ // State to store our value
14+ // Pass initial state function to useState so logic is only executed once
15+ const [storedValue, setStoredValue] = useState<T>(() => {
16+ if (typeof window === "undefined") {
17+ return initialValue;
18+ }
19+ try {
20+ // Get from local storage by key
21+ const item = window.localStorage.getItem(key);
22+ if (!item) {
23+ return initialValue;
24+ }
25+ // Parse stored json or if none return initialValue
26+ return JSON.parse(item) as T;
27+ } catch {
28+ // If error, clear invalid value and return initialValue
29+ window.localStorage.removeItem(key);
30+ return initialValue;
31+ }
32+ });
33+
34+ // Return a wrapped version of useState's setter function that
35+ // persists the new value to localStorage.
36+ const setValue = (value: T | ((prev: T) => T)) => {
37+ try {
38+ // Allow value to be a function so we have same API as useState
39+ const valueToStore = value instanceof Function ? value(storedValue) : value;
40+ // Save state
41+ setStoredValue(valueToStore);
42+ // Save to local storage
43+ if (typeof window !== "undefined") {
44+ window.localStorage.setItem(key, JSON.stringify(valueToStore));
45+ }
46+ } catch (error) {
47+ // A more advanced implementation would handle the error case
48+ console.error(`Error setting localStorage key "${key}":`, error);
49+ }
50+ };
51+
52+ return [storedValue, setValue];
53+}
src/hooks/useMessages.ts+2−10
@@ -47,14 +47,9 @@ export function useMessages(
4747 const sendMessage = async (
4848 message: string,
4949 currentThreadId: number | null,
50- onCreateThread: (
51- title?: string,
52- firstMessage?: string
53- ) => Promise<number | null>,
50+ onCreateThread: (title?: string, firstMessage?: string) => Promise<number | null>,
5451 onThreadSelect: (id: number) => void,
5552 onThreadsReload: () => void,
56- selectedModel: string = "gpt-oss",
57- maxPromptLength?: "none" | 1024 | 4096,
5853 onError?: (error: string) => void
5954 ) => {
6055 if (!message.trim() || isLoading) return;
@@ -65,10 +60,7 @@ export function useMessages(
6560 if (!targetThreadId) {
6661 // Create a new thread if none exists
6762 // The onCreateThread callback should already have model and maxPromptLength
68- targetThreadId = await onCreateThread(
69- message.substring(0, 100),
70- message
71- );
63+ targetThreadId = await onCreateThread(message.substring(0, 100), message);
7264 if (!targetThreadId) {
7365 setIsLoading(false);
7466 if (onError) {
src/hooks/useSettings.ts+0−88
@@ -1,88 +0,0 @@
1-import { useState, useEffect } from "react";
2-
3-export function useSettings(onError?: (error: string) => void) {
4- const [location, setLocation] = useState<string>("");
5-
6- // Load settings from API
7- useEffect(() => {
8- const loadSettings = async () => {
9- try {
10- // Load saved settings from API
11- const settingsRes = await fetch("/api/settings");
12- if (!settingsRes.ok) {
13- const errorData = await settingsRes.json().catch((parseError) => {
14- throw new Error(
15- `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
16- );
17- });
18- throw new Error(errorData.error || settingsRes.statusText);
19- }
20- const settingsData = await settingsRes.json();
21- const settings = settingsData.settings || {};
22- const savedLocation = settings.location || "";
23-
24- // Get browser timezone and post current time in ISO format to settings on app start
25- const browserTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
26- const currentTimeISO = new Date().toISOString();
27-
28- // Use timezone as default location if no location is set
29- const locationToUse = savedLocation || browserTimezone;
30- setLocation(locationToUse);
31-
Cut short: this commit's diff is over 1000 lines.
src/hooks/useTheme.ts+6−9
Cut short: this commit's diff is over 1000 lines.
src/hooks/useThreads.ts+5−2
Cut short: this commit's diff is over 1000 lines.
src/lib/db/schema.ts+1−0
Cut short: this commit's diff is over 1000 lines.
src/lib/ollama/chat/system-prompt.ts+67−0
Cut short: this commit's diff is over 1000 lines.
src/lib/ollama/tools/weather.ts+2−7
Cut short: this commit's diff is over 1000 lines.
tsconfig.tsbuildinfo+1−1
Cut short: this commit's diff is over 1000 lines.