xonecas.io
53129
Pa

PAT / commit a004f7c

fix: lint, typecheck and format

xonecas2025-12-18 a004f7cfb2cf29715f5e6c50868d2f8e105f950b parent a04f73e

31 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.

AGENTS.md+2−2
@@ -112,8 +112,8 @@ Add tests when prompted only.
112112 3. Update existing tests and add more if prompted to.
113113 4. Format code: `npm run format`
114114 5. Check for errors in compilation: `npm run typecheck`
115-5. Run linter: `npm run lint`
116-6. Run tests: `npm run test:run` (verify all tests pass)
115+6. Run linter: `npm run lint` **NEVER USE IGNORE COMMENTS**
116+7. Run tests: `npm run test:run` (verify all tests pass)
117117
118118 ## Important Constraints
119119
app/api/chat/route.ts+16−208
@@ -1,6 +1,5 @@
11 import { NextResponse } from "next/server";
22 import {
3- fetchOllamaResponse,
43 type OllamaMessageInput,
54 type OllamaMessageRole,
65 type MaxPromptLength,
@@ -8,11 +7,16 @@ import {
87 import { db } from "@/src/lib/db";
98 import { messages, threads } from "@/src/lib/db/schema";
109 import { eq, asc } from "drizzle-orm";
10+import { streamAssistantResponse } from "@/src/lib/chat";
1111
1212 export async function POST(request: Request) {
1313 const { message, threadId: threadIdRaw } = await request.json();
1414 const signal = request.signal;
1515
16+ if (typeof message !== "string" || !message.trim()) {
17+ return NextResponse.json({ error: "message is required " }, { status: 400 });
18+ }
19+
1620 if (!threadIdRaw) {
1721 return NextResponse.json({ error: "threadId is required" }, { status: 400 });
1822 }
@@ -25,21 +29,15 @@ export async function POST(request: Request) {
2529 try {
2630 // 1. Fetch thread to get its model and maxPromptLength settings
2731 // These thread-specific settings override any global settings
28- const thread = await db
29- .select()
30- .from(threads)
31- .where(eq(threads.id, threadId))
32- .limit(1);
32+ const thread = await db.select().from(threads).where(eq(threads.id, threadId)).limit(1);
3333 if (thread.length === 0) {
3434 return NextResponse.json({ error: "Thread not found" }, { status: 404 });
3535 }
36- // Use thread-specific model (stored in thread table)
37- const threadModel = thread[0].model || "gpt-oss";
38- // Use thread-specific maxPromptLength (stored in thread table, can be null, 1024, or 4096)
39- // Type assertion ensures compatibility with fetchOllamaResponse which expects "none" | 1024 | 4096 | null
36+ // Use thread-specific settings (stored in thread table)
37+ const threadModel = thread[0].model;
4038 // Note: null from database means "none" (no limit), which fetchOllamaResponse handles correctly
4139 const threadMaxPromptLength: MaxPromptLength =
42- thread[0].maxPromptLength === null ? 'none' : thread[0].maxPromptLength as MaxPromptLength;
40+ thread[0].maxPromptLength === null ? null : (thread[0].maxPromptLength as MaxPromptLength);
4341
4442 // 2. Fetch previous messages from thread
4543 const previousMessages = await db
@@ -70,202 +68,12 @@ export async function POST(request: Request) {
7068 });
7169
7270 // 5. Stream assistant response
73- let accumulatedContent = "";
74- let accumulatedThinking = "";
75- const allToolCalls: any[] = [];
76-
77- const encoder = new TextEncoder();
78- const stream = new ReadableStream({
79- async start(controller) {
80- // Track if controller is closed to avoid double-close
81- let isControllerClosed = false;
82- const safeClose = () => {
83- if (!isControllerClosed) {
84- isControllerClosed = true;
85- try {
86- controller.close();
87- } catch (e) {
88- // Controller may already be closed, ignore
89- }
90- }
91- };
92-
93- try {
94- // Check if already aborted
95- if (signal.aborted) {
96- safeClose();
97- return;
98- }
99-
100- const onChunk = (chunk: { content?: string; thinking?: string; toolCalls?: any[] }) => {
101- // Check abort signal before each chunk
102- if (signal.aborted || isControllerClosed) {
103- return;
104- }
105-
106- try {
107- if (chunk.content) {
108- accumulatedContent += chunk.content;
109- controller.enqueue(
110- encoder.encode(
111- `data: ${JSON.stringify({ type: "content", content: chunk.content })}\n\n`
112- )
113- );
114- }
115- if (chunk.thinking) {
116- accumulatedThinking += chunk.thinking;
117- controller.enqueue(
118- encoder.encode(
119- `data: ${JSON.stringify({ type: "thinking", thinking: chunk.thinking })}\n\n`
120- )
121- );
122- }
123- if (chunk.toolCalls) {
124- allToolCalls.push(...chunk.toolCalls);
125- controller.enqueue(
126- encoder.encode(
127- `data: ${JSON.stringify({ type: "toolCalls", toolCalls: chunk.toolCalls })}\n\n`
128- )
129- );
130- }
131- } catch (e) {
132- // Controller may be closed, ignore
133- }
134- };
135-
136- // Set up abort handler
137- const abortHandler = () => {
138- if (!isControllerClosed) {
139- try {
140- controller.enqueue(
141- encoder.encode(
142- `data: ${JSON.stringify({ type: "error", error: "Generation stopped" })}\n\n`
143- )
144- );
145- } catch (e) {
146- // Controller may be closed, ignore
147- }
148- safeClose();
149- }
150- };
151- signal.addEventListener("abort", abortHandler);
152-
153- let generationTimeMs: number | undefined;
154- let toolCalls: any[] | undefined;
155-
156- try {
157- const result = await fetchOllamaResponse(
158- ollamaMessages,
159- onChunk,
160- threadModel,
161- signal,
162- threadMaxPromptLength
163- );
164- generationTimeMs = result.generationTimeMs;
165- toolCalls = result.toolCalls;
166- } catch (error) {
167- // If aborted, don't throw - just close
168- if (signal.aborted || (error instanceof Error && error.message === "Request aborted")) {
169- safeClose();
170- return;
171- }
172- throw error;
173- } finally {
174- signal.removeEventListener("abort", abortHandler);
175- }
176-
177- // Check if aborted before saving
178- if (signal.aborted) {
179- // Save partial content if any was generated
180- if (accumulatedContent) {
181- await db.insert(messages).values({
182- threadId: threadId,
183- role: "assistant",
184- content: accumulatedContent,
185- model: threadModel,
186- maxPromptLength: threadMaxPromptLength === "none" ? null : threadMaxPromptLength, // null means "none" (no limit), otherwise 1024 or 4096
187- createdAt: new Date(),
188- generationTimeMs: null,
189- toolCalls: allToolCalls.length > 0 ? JSON.stringify(allToolCalls) : null,
190- });
191- await db
192- .update(threads)
193- .set({ updatedAt: new Date() })
194- .where(eq(threads.id, threadId));
195-
196- // Send done message with metadata for aborted generation
197- if (!isControllerClosed) {
198- try {
199- controller.enqueue(
200- encoder.encode(
201- `data: ${JSON.stringify({
202- type: "done",
203- answer: accumulatedContent,
204- model: threadModel,
205- maxPromptLength: threadMaxPromptLength,
206- })}\n\n`
207- )
208- );
209- } catch (e) {
210- // Controller may be closed, ignore
211- }
212- }
213- }
214- safeClose();
215- return;
216- }
217-
218- // 6. Store assistant message with model, maxPromptLength, generation time and tool calls
219- await db.insert(messages).values({
220- threadId: threadId,
221- role: "assistant",
222- content: accumulatedContent,
223- model: threadModel,
224- maxPromptLength: threadMaxPromptLength === "none" ? null : threadMaxPromptLength, // null means "none" (no limit), otherwise 1024 or 4096
225- createdAt: new Date(),
226- generationTimeMs,
227- toolCalls: toolCalls ? JSON.stringify(toolCalls) : null,
228- });
229-
230- // 7. Update thread's updatedAt timestamp
231- await db
232- .update(threads)
233- .set({ updatedAt: new Date() })
234- .where(eq(threads.id, threadId));
235-
236- // Send final message with metadata
237- if (!isControllerClosed) {
238- try {
239- controller.enqueue(
240- encoder.encode(
241- `data: ${JSON.stringify({
242- type: "done",
243- answer: accumulatedContent,
244- model: threadModel,
245- maxPromptLength: threadMaxPromptLength,
246- })}\n\n`
247- )
248- );
249- } catch (e) {
250- // Controller may be closed, ignore
251- }
252- safeClose();
253- }
254- } catch (error) {
255- if (!isControllerClosed) {
256- try {
257- controller.enqueue(
258- encoder.encode(
259- `data: ${JSON.stringify({ type: "error", error: "Sorry, something went wrong." })}\n\n`
260- )
261- );
262- } catch (e) {
263- // Controller may be closed, ignore
264- }
265- safeClose();
266- }
267- }
268- },
71+ const stream = streamAssistantResponse({
72+ ollamaMessages,
73+ threadId,
74+ threadModel,
75+ threadMaxPromptLength,
76+ signal,
26977 });
27078
27179 return new Response(stream, {
@@ -275,7 +83,7 @@ export async function POST(request: Request) {
27583 Connection: "keep-alive",
27684 },
27785 });
278- } catch (error) {
86+ } catch {
27987 return NextResponse.json({ answer: "Sorry, something went wrong." }, { status: 500 });
28088 }
28189 }
app/api/models/route.ts+1−1
@@ -11,7 +11,7 @@ export async function GET() {
1111 model: model.name, // Use name as the model identifier
1212 }));
1313 return NextResponse.json({ models });
14- } catch (error) {
14+ } catch {
1515 return NextResponse.json({ error: "Failed to fetch models" }, { status: 500 });
1616 }
1717 }
app/api/settings/route.ts+3−3
@@ -14,7 +14,7 @@ export async function GET() {
1414 return NextResponse.json({
1515 settings: settings || { maxPromptLength: "none", selectedModel: "gpt-oss" },
1616 });
17- } catch (error) {
17+ } catch {
1818 return NextResponse.json({ error: "Failed to get settings" }, { status: 500 });
1919 }
2020 }
@@ -23,7 +23,7 @@ export async function POST(request: Request) {
2323 try {
2424 const { maxPromptLength, selectedModel } = await request.json();
2525
26- const settings: Settings = {};
26+ const settings: Partial<Settings> = {};
2727
2828 // Validate and set maxPromptLength if provided
2929 if (maxPromptLength !== undefined) {
@@ -51,7 +51,7 @@ export async function POST(request: Request) {
5151 await setCache(SETTINGS_CACHE_KEY, mergedSettings);
5252
5353 return NextResponse.json({ settings: mergedSettings });
54- } catch (error) {
54+ } catch {
5555 return NextResponse.json({ error: "Failed to set settings" }, { status: 500 });
5656 }
5757 }
app/api/threads/[id]/messages/[messageId]/route.ts+1−1
@@ -30,7 +30,7 @@ export async function DELETE(
3030 }
3131
3232 return NextResponse.json({ success: true });
33- } catch (error) {
33+ } catch {
3434 return NextResponse.json({ error: "Failed to delete message" }, { status: 500 });
3535 }
3636 }
app/api/threads/[id]/messages/route.ts+1−1
@@ -18,7 +18,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ id:
1818 .orderBy(asc(messages.createdAt));
1919
2020 return NextResponse.json({ messages: messagesList });
21- } catch (error) {
21+ } catch {
2222 return NextResponse.json({ error: "Failed to get messages" }, { status: 500 });
2323 }
2424 }
app/api/threads/[id]/route.ts+2−2
@@ -38,7 +38,7 @@ export async function PATCH(request: Request, { params }: { params: Promise<{ id
3838 }
3939
4040 return NextResponse.json({ thread: updatedThread[0] });
41- } catch (error) {
41+ } catch {
4242 return NextResponse.json({ error: "Failed to update thread" }, { status: 500 });
4343 }
4444 }
@@ -59,7 +59,7 @@ export async function DELETE(request: Request, { params }: { params: Promise<{ i
5959 }
6060
6161 return NextResponse.json({ success: true });
62- } catch (error) {
62+ } catch {
6363 return NextResponse.json({ error: "Failed to delete thread" }, { status: 500 });
6464 }
6565 }
app/api/threads/route.ts+2−2
@@ -33,7 +33,7 @@ export async function POST(request: Request) {
3333 });
3434
3535 return NextResponse.json({ thread: newThread[0] });
36- } catch (error) {
36+ } catch {
3737 return NextResponse.json({ error: "Failed to create thread" }, { status: 500 });
3838 }
3939 }
@@ -56,7 +56,7 @@ export async function GET(request: Request) {
5656 const hasMore = offset + limit < totalCount;
5757
5858 return NextResponse.json({ threads: threadsList, hasMore, totalCount });
59- } catch (error) {
59+ } catch {
6060 return NextResponse.json({ error: "Failed to get threads" }, { status: 500 });
6161 }
6262 }
app/page.tsx+4−12
@@ -44,10 +44,6 @@ export default function Home() {
4444 deleteMessageInternal(messageId, threadId, setError);
4545 };
4646
47- // Clear error when thread changes
48- useEffect(() => {
49- setError(null);
50- }, [currentThreadId]);
5147
5248 // Auto-dismiss error after 3 seconds
5349 useEffect(() => {
@@ -60,6 +56,7 @@ export default function Home() {
6056 }, [error]);
6157
6258 const handleThreadSelect = (threadId: number) => {
59+ setError(null);
6360 selectThread(threadId);
6461 };
6562
@@ -126,11 +123,6 @@ export default function Home() {
126123 }
127124 };
128125
129- // Get the model name for the current thread, or use selected model if no thread
130- const currentModelName =
131- currentThreadId !== null
132- ? threads.find((t) => t.id === currentThreadId)?.model || selectedModel || "gpt-oss"
133- : selectedModel || "gpt-oss";
134126
135127 return (
136128 <div className="flex h-screen bg-neutral-100 text-neutral-800 dark:bg-neutral-950 dark:text-neutral-200">
@@ -156,7 +148,6 @@ export default function Home() {
156148 ) : (
157149 <MessageList
158150 messages={messages}
159- streamingMessageId={streamingMessageId}
160151 threadId={currentThreadId}
161152 onDeleteMessage={handleDeleteMessage}
162153 />
@@ -169,7 +160,6 @@ export default function Home() {
169160 isLoadingMessages={isLoadingMessages}
170161 messages={messages}
171162 onSubmit={handleSendMessage}
172- modelName={currentModelName}
173163 isStreaming={isLoading && streamingMessageId !== null}
174164 onStop={stopGeneration}
175165 error={error}
@@ -189,7 +179,9 @@ export default function Home() {
189179 onCreateNewThread={handleCreateNewThread}
190180 onThreadSelect={handleThreadSelect}
191181 onThemeChange={handleThemeChange}
192- onLoadMore={(limit) => loadMoreThreads(limit, setError)}
182+ onLoadMore={() => {
183+ void loadMoreThreads(8, setError);
184+ }}
193185 hasMoreThreads={hasMoreThreads}
194186 />
195187 </div>
eslint.config.mjs+10−11
@@ -1,7 +1,7 @@
1-import { defineConfig, globalIgnores } from 'eslint/config'
2-import nextVitals from 'eslint-config-next/core-web-vitals'
3-import nextTs from 'eslint-config-next/typescript'
4-import prettier from 'eslint-config-prettier/flat'
1+import { defineConfig, globalIgnores } from "eslint/config";
2+import nextVitals from "eslint-config-next/core-web-vitals";
3+import nextTs from "eslint-config-next/typescript";
4+import prettier from "eslint-config-prettier/flat";
55
66 const eslintConfig = defineConfig([
77 ...nextVitals,
@@ -10,12 +10,11 @@ const eslintConfig = defineConfig([
1010 // Override default ignores of eslint-config-next.
1111 globalIgnores([
1212 // Default ignores of eslint-config-next:
13- '.next/**',
14- 'out/**',
15- 'build/**',
16- 'next-env.d.ts',
13+ ".next/**",
14+ "out/**",
15+ "build/**",
16+ "next-env.d.ts",
1717 ]),
18-])
19-
20-export default eslintConfig
18+]);
2119
20+export default eslintConfig;
src/components/ErrorNotification.tsx+0−2
@@ -14,5 +14,3 @@ export default function ErrorNotification({ message }: ErrorNotificationProps) {
1414 </div>
1515 );
1616 }
17-
18-
src/components/MessageInput.tsx+17−19
@@ -14,7 +14,6 @@ type MessageInputProps = {
1414 isLoadingMessages: boolean;
1515 messages: Message[];
1616 onSubmit: (message: string) => void;
17- modelName?: string;
1817 isStreaming?: boolean;
1918 onStop?: () => void;
2019 error?: string | null;
@@ -33,24 +32,23 @@ export type MessageInputRef = {
3332 };
3433
3534 const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
36- (
37- {
38- isLoading,
39- isLoadingMessages,
40- messages,
41- onSubmit,
42- modelName = "gpt-oss",
43- isStreaming = false,
44- onStop,
45- error,
46- currentThreadId,
47- currentThread,
48- onThreadUpdate,
49- onThreadDelete,
50- onError,
51- },
52- ref
53- ) => {
35+ (
36+ {
37+ isLoading,
38+ isLoadingMessages,
39+ messages,
40+ onSubmit,
41+ isStreaming = false,
42+ onStop,
43+ error,
44+ currentThreadId,
45+ currentThread,
46+ onThreadUpdate,
47+ onThreadDelete,
48+ onError,
49+ },
50+ ref
51+ ) => {
5452 const [input, setInput] = useState("");
5553 const [historyIndex, setHistoryIndex] = useState<number | null>(null);
5654 const textareaRef = useRef<HTMLTextAreaElement>(null);
src/components/MessageList/AssistantMessage.tsx+2−3
@@ -8,10 +8,9 @@ import "../../../app/highlight-theme.css";
88
99 type AssistantMessageProps = {
1010 message: Message;
11- isStreaming?: boolean;
1211 };
1312
14-export default function AssistantMessage({ message, isStreaming = false }: AssistantMessageProps) {
13+export default function AssistantMessage({ message }: AssistantMessageProps) {
1514 const formatTimestamp = (date: Date | string): string => {
1615 const d = typeof date === "string" ? new Date(date) : date;
1716 return d.toLocaleString();
@@ -31,7 +30,7 @@ export default function AssistantMessage({ message, isStreaming = false }: Assis
3130
3231 // Count occurrences of each tool name
3332 const toolCounts: Record<string, number> = {};
34- toolCalls.forEach((tc: any) => {
33+ toolCalls.forEach((tc: { function?: { name?: string } }) => {
3534 const toolName = tc.function?.name || "unknown";
3635 toolCounts[toolName] = (toolCounts[toolName] || 0) + 1;
3736 });
src/components/MessageList/index.tsx+1−3
@@ -8,14 +8,12 @@ import DeleteMessageButton from "./DeleteMessageButton";
88
99 type MessageListProps = {
1010 messages: Message[];
11- streamingMessageId: number | null;
1211 threadId: number | null;
1312 onDeleteMessage: (messageId: number, threadId: number) => void;
1413 };
1514
1615 export default function MessageList({
1716 messages,
18- streamingMessageId,
1917 threadId,
2018 onDeleteMessage,
2119 }: MessageListProps) {
@@ -50,7 +48,7 @@ export default function MessageList({
5048 >
5149 <div className="p-2">
5250 {msg.role === "assistant" ? (
53- <AssistantMessage message={msg} isStreaming={streamingMessageId === msg.id} />
51+ <AssistantMessage message={msg} />
5452 ) : (
5553 <UserMessage message={msg} />
5654 )}
src/components/NoThreadSelected.tsx+28−20
@@ -19,13 +19,11 @@ export default function NoThreadSelected({
1919 onMaxPromptLengthChange,
2020 onError,
2121 }: NoThreadSelectedProps) {
22- const [currentTime, setCurrentTime] = useState<Date | null>(null);
22+ const [currentTime, setCurrentTime] = useState<Date>(() => new Date());
2323 const [models, setModels] = useState<Array<{ name: string; model: string }>>([]);
2424 const [isLoadingModels, setIsLoadingModels] = useState(false);
2525
2626 useEffect(() => {
27- // Set initial time only on client side to avoid hydration mismatch
28- setCurrentTime(new Date());
2927 const timer = setInterval(() => {
3028 setCurrentTime(new Date());
3129 }, 1000);
@@ -34,28 +32,38 @@ export default function NoThreadSelected({
3432 }, []);
3533
3634 useEffect(() => {
37- setIsLoadingModels(true);
38- fetch("/api/models")
39- .then(async (res) => {
35+ let cancelled = false;
36+ const loadModels = async () => {
37+ setIsLoadingModels(true);
38+ try {
39+ const res = await fetch("/api/models");
4040 if (!res.ok) {
4141 const errorData = await res.json().catch((parseError) => {
42- throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
42+ throw new Error(
43+ `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
44+ );
4345 });
4446 throw new Error(errorData.error || res.statusText);
4547 }
46- return res.json();
47- })
48- .then((data) => {
49- const availableModels = data.models || [];
50- setModels(availableModels);
51- setIsLoadingModels(false);
52- })
53- .catch((error) => {
54- setIsLoadingModels(false);
55- if (onError && error instanceof Error) {
56- onError(error.message);
48+ const data = await res.json();
49+ if (!cancelled) {
50+ const availableModels = data.models || [];
51+ setModels(availableModels);
52+ setIsLoadingModels(false);
5753 }
58- });
54+ } catch (error) {
55+ if (!cancelled) {
56+ setIsLoadingModels(false);
57+ if (onError && error instanceof Error) {
58+ onError(error.message);
59+ }
60+ }
61+ }
62+ };
63+ loadModels();
64+ return () => {
65+ cancelled = true;
66+ };
5967 }, [onError]);
6068
6169 const formatTime = (date: Date): string => {
@@ -67,7 +75,7 @@ export default function NoThreadSelected({
6775 return (
6876 <div className="mx-auto min-w-0 max-w-5xl">
6977 <div className="flex flex-col gap-4 bg-neutral-200 p-8 dark:bg-neutral-900">
70- <h1 className="text-4xl font-bold">Hello, I'm PAT 👋</h1>
78+ <h1 className="text-4xl font-bold">Hello, I&apos;m PAT 👋</h1>
7179 <p>
7280 <strong>PAT</strong> (Personal Assistant Thing) is your personal assistant. Start typing
7381 below to start new a conversation thread or pick a previous conversation thread from the
src/components/ThreadSettingsModal.tsx+4−6
@@ -42,7 +42,9 @@ export default function ThreadSettingsModal({
4242 .then(async (res) => {
4343 if (!res.ok) {
4444 const errorData = await res.json().catch((parseError) => {
45- throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
45+ throw new Error(
46+ `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
47+ );
4648 });
4749 throw new Error(errorData.error || res.statusText);
4850 }
@@ -60,7 +62,7 @@ export default function ThreadSettingsModal({
6062 }
6163 });
6264 }
63- }, [isOpen]);
65+ }, [isOpen, onError]);
6466
6567 // Load thread settings when thread changes
6668 useEffect(() => {
@@ -123,10 +125,6 @@ export default function ThreadSettingsModal({
123125 }
124126
125127 const threadTitle = thread.title || `Thread ${thread.id}`;
126- const hasChanges =
127- selectedModel !== (thread.model || "gpt-oss") ||
128- maxPromptLength !==
129- (thread.maxPromptLength === null ? "none" : (thread.maxPromptLength as 1024 | 4096));
130128
131129 return (
132130 <Modal isOpen={isOpen} onClose={onClose}>
src/components/buttons/SecondaryButton.tsx+1−1
@@ -1,7 +1,7 @@
11 "use client";
22
33 import type { AnchorHTMLAttributes, ReactNode } from "react";
4-import { Children, isValidElement } from "react";
4+import { Children } from "react";
55
66 type SecondaryButtonProps = AnchorHTMLAttributes<HTMLAnchorElement> & {
77 children: ReactNode;
src/components/icons/ErrorIcon.tsx+0−2
@@ -16,5 +16,3 @@ export default function ErrorIcon({ className }: { className?: string }) {
1616 </svg>
1717 );
1818 }
19-
20-
src/hooks/useMessages.ts+37−36
@@ -9,27 +9,24 @@ export function useMessages(threadId: number | null, onError?: (error: string) =
99 const sendingToThreadIdRef = useRef<number | null>(null);
1010 const abortControllerRef = useRef<AbortController | null>(null);
1111
12- const loadMessages = useCallback(
13- async (id: number, onError?: (error: string) => void) => {
14- setIsLoadingMessages(true);
15- try {
16- const res = await fetch(`/api/threads/${id}/messages`);
17- if (!res.ok) {
18- throw new Error(`Failed to load messages: ${res.status}`);
19- }
20- const data = await res.json();
21- const loadedMessages = data.messages || [];
22- setMessages(loadedMessages);
23- } catch (error) {
24- if (onError && error instanceof Error) {
25- onError(error.message);
26- }
27- } finally {
28- setIsLoadingMessages(false);
12+ const loadMessages = useCallback(async (id: number, onError?: (error: string) => void) => {
13+ setIsLoadingMessages(true);
14+ try {
15+ const res = await fetch(`/api/threads/${id}/messages`);
16+ if (!res.ok) {
17+ throw new Error(`Failed to load messages: ${res.status}`);
2918 }
30- },
31- []
32- );
19+ const data = await res.json();
20+ const loadedMessages = data.messages || [];
21+ setMessages(loadedMessages);
22+ } catch (error) {
23+ if (onError && error instanceof Error) {
24+ onError(error.message);
25+ }
26+ } finally {
27+ setIsLoadingMessages(false);
28+ }
29+ }, []);
3330
3431 useEffect(() => {
3532 if (threadId !== null) {
@@ -63,22 +60,22 @@ export function useMessages(threadId: number | null, onError?: (error: string) =
6360 setIsLoading(true);
6461 let targetThreadId = currentThreadId;
6562
63+ if (!targetThreadId) {
64+ // Create a new thread if none exists
65+ // Use the validated selectedModel instead of reading from localStorage
66+ targetThreadId = await onCreateThread(
67+ message.substring(0, 100),
68+ message,
69+ selectedModel,
70+ maxPromptLength
71+ );
6672 if (!targetThreadId) {
67- // Create a new thread if none exists
68- // Use the validated selectedModel instead of reading from localStorage
69- targetThreadId = await onCreateThread(
70- message.substring(0, 100),
71- message,
72- selectedModel,
73- maxPromptLength
74- );
75- if (!targetThreadId) {
76- setIsLoading(false);
77- if (onError) {
78- onError("Failed to create thread");
79- }
80- return;
73+ setIsLoading(false);
74+ if (onError) {
75+ onError("Failed to create thread");
8176 }
77+ return;
78+ }
8279 // Mark that we're sending to this thread before selecting it
8380 sendingToThreadIdRef.current = targetThreadId;
8481 onThreadSelect(targetThreadId);
@@ -128,7 +125,9 @@ export function useMessages(threadId: number | null, onError?: (error: string) =
128125
129126 if (!res.ok) {
130127 const errorData = await res.json().catch((parseError) => {
131- throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
128+ throw new Error(
129+ `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
130+ );
132131 });
133132 throw new Error(errorData.error || `HTTP error! status: ${res.status}`);
134133 }
@@ -247,7 +246,9 @@ export function useMessages(threadId: number | null, onError?: (error: string) =
247246 });
248247 if (!res.ok) {
249248 const errorData = await res.json().catch((parseError) => {
250- throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
249+ throw new Error(
250+ `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
251+ );
251252 });
252253 throw new Error(errorData.error || "Failed to delete message");
253254 }
src/hooks/useModelSettings.ts+13−5
@@ -12,7 +12,9 @@ export function useModelSettings(onError?: (error: string) => void) {
1212 const settingsRes = await fetch("/api/settings");
1313 if (!settingsRes.ok) {
1414 const errorData = await settingsRes.json().catch((parseError) => {
15- throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
15+ throw new Error(
16+ `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
17+ );
1618 });
1719 throw new Error(errorData.error || settingsRes.statusText);
1820 }
@@ -25,7 +27,9 @@ export function useModelSettings(onError?: (error: string) => void) {
2527 const modelsRes = await fetch("/api/models");
2628 if (!modelsRes.ok) {
2729 const errorData = await modelsRes.json().catch((parseError) => {
28- throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
30+ throw new Error(
31+ `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
32+ );
2933 });
3034 throw new Error(errorData.error || modelsRes.statusText);
3135 }
@@ -71,7 +75,7 @@ export function useModelSettings(onError?: (error: string) => void) {
7175 };
7276
7377 loadAndValidateSettings();
74- }, []);
78+ }, [onError]);
7579
7680 const handleModelChange = async (model: string) => {
7781 setSelectedModel(model);
@@ -84,7 +88,9 @@ export function useModelSettings(onError?: (error: string) => void) {
8488 });
8589 if (!res.ok) {
8690 const errorData = await res.json().catch((parseError) => {
87- throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
91+ throw new Error(
92+ `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
93+ );
8894 });
8995 throw new Error(errorData.error || res.statusText);
9096 }
@@ -106,7 +112,9 @@ export function useModelSettings(onError?: (error: string) => void) {
106112 });
107113 if (!res.ok) {
108114 const errorData = await res.json().catch((parseError) => {
109- throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
115+ throw new Error(
116+ `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
117+ );
110118 });
111119 throw new Error(errorData.error || res.statusText);
112120 }
src/hooks/useTheme.ts+9−6
@@ -1,7 +1,13 @@
11 import { useState, useEffect } from "react";
22
33 export function useTheme() {
4- const [themeMode, setThemeMode] = useState<"device" | "dark" | "light">("device");
4+ const [themeMode, setThemeMode] = useState<"device" | "dark" | "light">(() => {
5+ if (typeof window !== "undefined") {
6+ const savedMode = localStorage.getItem("themeMode") as "device" | "dark" | "light" | null;
7+ return savedMode || "device";
8+ }
9+ return "device";
10+ });
511
612 const applyTheme = (mode: "device" | "dark" | "light") => {
713 let shouldBeDark = false;
@@ -19,11 +25,8 @@ export function useTheme() {
1925 };
2026
2127 useEffect(() => {
22- const savedMode = localStorage.getItem("themeMode") as "device" | "dark" | "light" | null;
23- const mode = savedMode || "device";
24- setThemeMode(mode);
25- applyTheme(mode);
26- }, []);
28+ applyTheme(themeMode);
29+ }, [themeMode]);
2730
2831 useEffect(() => {
2932 if (themeMode === "device") {
src/hooks/useThreads.ts+17−15
@@ -17,11 +17,11 @@ export function useThreads() {
1717 setThreads(threadsList);
1818 setHasMoreThreads(data.hasMore || false);
1919 setTotalThreadCount(data.totalCount || 0);
20- } catch (error) {
21- if (onError && error instanceof Error) {
22- onError(error.message);
23- }
20+ } catch (error) {
21+ if (onError && error instanceof Error) {
22+ onError(error.message);
2423 }
24+ }
2525 };
2626
2727 const loadMoreThreads = async (limit: number = 8, onError?: (error: string) => void) => {
@@ -39,11 +39,11 @@ export function useThreads() {
3939 } else {
4040 setHasMoreThreads(false);
4141 }
42- } catch (error) {
43- if (onError && error instanceof Error) {
44- onError(error.message);
45- }
42+ } catch (error) {
43+ if (onError && error instanceof Error) {
44+ onError(error.message);
4645 }
46+ }
4747 };
4848
4949 const createThread = async (
@@ -67,7 +67,7 @@ export function useThreads() {
6767 const settingsRes = await fetch("/api/settings");
6868 const settingsData = await settingsRes.json();
6969 maxPromptLengthToUse = settingsData.settings?.maxPromptLength || "none";
70- } catch (error) {
70+ } catch {
7171 maxPromptLengthToUse = "none";
7272 }
7373 }
@@ -112,7 +112,9 @@ export function useThreads() {
112112 });
113113 if (!res.ok) {
114114 const errorData = await res.json().catch((parseError) => {
115- throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
115+ throw new Error(
116+ `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
117+ );
116118 });
117119 throw new Error(errorData.error || "Failed to update thread");
118120 }
@@ -122,8 +124,7 @@ export function useThreads() {
122124 // Update the thread in local state
123125 setThreads((prev) => prev.map((t) => (t.id === threadId ? updatedThread : t)));
124126 } catch (error) {
125- const errorMsg =
126- error instanceof Error ? error.message : "Failed to update thread";
127+ const errorMsg = error instanceof Error ? error.message : "Failed to update thread";
127128 if (onError) onError(errorMsg);
128129 throw error;
129130 }
@@ -139,7 +140,9 @@ export function useThreads() {
139140 });
140141 if (!res.ok) {
141142 const errorData = await res.json().catch((parseError) => {
142- throw new Error(`Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`);
143+ throw new Error(
144+ `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
145+ );
143146 });
144147 throw new Error(errorData.error || "Failed to delete thread");
145148 }
@@ -147,8 +150,7 @@ export function useThreads() {
147150 setThreads((prev) => prev.filter((t) => t.id !== threadId));
148151 setTotalThreadCount((prev) => Math.max(0, prev - 1));
149152 } catch (error) {
150- const errorMsg =
151- error instanceof Error ? error.message : "Failed to delete thread";
153+ const errorMsg = error instanceof Error ? error.message : "Failed to delete thread";
152154 if (onError) onError(errorMsg);
153155 throw error;
154156 }
src/lib/cache/index.ts+6−4
@@ -26,8 +26,9 @@ export async function setCache<T>(key: string, value: T, ttlMs?: number): Promis
2626 await valkey.set(key, serialized);
2727 debug(`[Cache] Set key: ${key}`);
2828 }
29- } catch (error: any) {
30- debug(`[Cache] Error setting cache: ${error.message}`);
29+ } catch (error: unknown) {
30+ const message = error instanceof Error ? error.message : String(error);
31+ debug(`[Cache] Error setting cache: ${message}`);
3132 // Don't throw - cache operations should continue even if persistence fails
3233 }
3334 }
@@ -49,8 +50,9 @@ export async function getCache<T>(key: string): Promise<T | null> {
4950
5051 debug(`[Cache] Cache hit for key: ${key}`);
5152 return JSON.parse(serialized) as T;
52- } catch (error: any) {
53- debug(`[Cache] Error getting cache: ${error.message}`);
53+ } catch (error: unknown) {
54+ const message = error instanceof Error ? error.message : String(error);
55+ debug(`[Cache] Error getting cache: ${message}`);
5456 return null;
5557 }
5658 }
src/lib/chat.ts+203−0
@@ -0,0 +1,203 @@
1+/* personal-assistant-thing/src/lib/chat.ts */
2+import {
3+ fetchOllamaResponse,
4+ type OllamaMessageInput,
5+ type MaxPromptLength,
6+ type ToolCall,
7+} from "@/src/lib/ollama";
8+import { db } from "@/src/lib/db";
9+import { messages, threads } from "@/src/lib/db/schema";
10+import { eq } from "drizzle-orm";
11+
12+export interface StreamAssistantResponseParams {
13+ ollamaMessages: OllamaMessageInput[];
14+ threadId: number;
15+ threadModel: string | null;
16+ threadMaxPromptLength: MaxPromptLength;
17+ signal: AbortSignal;
18+}
19+
20+/**
21+ * Streams assistant response and handles database persistence
22+ */
Cut short: this commit's diff is over 1000 lines.
src/lib/debug.ts+1−1
Cut short: this commit's diff is over 1000 lines.
src/lib/ollama/duckduckgo.ts+1−1
Cut short: this commit's diff is over 1000 lines.
src/lib/ollama/index.ts+16−21
Cut short: this commit's diff is over 1000 lines.
src/lib/ollama/types.ts+18−5
Cut short: this commit's diff is over 1000 lines.
src/lib/ratelimit.ts+0−1
Cut short: this commit's diff is over 1000 lines.
tailwind.config.js+6−2
Cut short: this commit's diff is over 1000 lines.
tsconfig.tsbuildinfo+1−1
Cut short: this commit's diff is over 1000 lines.