xonecas.io
53129
Pa

PAT / commit 4870117

fix: several small bug fixes resulting from the refactor

xonecas2025-12-21 487011744e054944f535baf2ea4c0624efdf2b7b parent 958effc

9 files changed

AGENTS.md+1−58
@@ -1,7 +1,5 @@
11 # Agent Instructions
22
3-## Important Instructions
4-
53 - **Never make assumptions** - Ask for clarification instead.
64 - **Never ignore errors, warnings, or issues** - Address them immediately.
75 - **Never install, uninstall, or delete anything** without explicit authorization.
@@ -10,65 +8,10 @@
108 - **Always do exactly what was asked** - Don't add anything that wasn't explicitly mentioned.
119 - **Always lint and typecheck** changes using `npm run lint` and `npm run typecheck`.
1210 - **Always write modular, testable code** - Prefer small, focused functions and components, focused on reusability.
11+- **Always** use absolute paths in import using path aliases: `@/` for imports (e.g., `@/src/components/...`).
1312 - **Always review your changes before committing**:
1413 - identify code repetition and consolidate
1514 - identify overly complex code and simplify
1615 - ensure code modularity and separation of concerns
1716 - ensure code respects project guidelines
1817 - ensure the code uses best practices for React and Next.js
19-
20-## Coding Guidelines
21-
22-### TypeScript
23-
24-- Use strict typing - avoid `any`, prefer type inference where appropriate.
25-- Export types/interfaces alongside implementations.
26-- Use the types provided by dependencies when possible, avoid creating types for 3rd party code.
27-- Use Drizzle ORM type inference: `typeof table.$inferSelect` and `typeof table.$inferInsert`.
28-
29-### Code Organization
30-
31-- Always use absolute paths in import using path aliases: `@/` for root imports (e.g., `@/src/components/...`).
32-- Follow modular structure: `src/components/`, `src/hooks/`, `src/lib/`, `app/api/`.
33-- Keep files focused - one main export per file when possible.
34-
35-### Documentation
36-
37-- Add JSDoc comments for exported functions with `@param` and `@returns`.
38-- Keep commenting to a minimum. We should only add comments when the code is not self-explanatory
39-
40-### Naming Conventions
41-
42-- `camelCase` for functions, variables, and hooks (e.g., `useLocalStorage`, `handleSubmit`).
43-- `PascalCase` for components, types, and interfaces (e.g., `MessageInput`, `MessageInputRef`).
44-- `kebab-case` for file names (except React components which use PascalCase).
45-
46-### React Patterns
47-
48-- Use functional components with hooks.
49-- Use `forwardRef` when ref forwarding is needed.
50-- Properly type component props and refs.
51-- Handle loading and error states explicitly.
52-
53-### Error Handling
54-
55-- Use try-catch blocks for async operations.
56-- Return proper HTTP status codes in API routes (400, 404, 500).
57-- Log errors using the `debug` utility from `@/src/lib/debug`.
58-
59-### Database
60-
61-- Use Drizzle ORM query builder patterns.
62-- Use `eq()`, `asc()`, `desc()` from `drizzle-orm` for queries.
63-
64-### Testing
65-
66-- Write tests using Vitest for complex logic.
67-- Keep tests in `src/tests/` mirroring the source structure.
68-
69-### Git Commit Messages
70-
71-- Use conventional commit format: `<type>: <description>`
72-- Types: `feat:` (new features), `fix:` (bug fixes), `refactor:` (code refactoring), `docs:` (documentation), `chore:` (maintenance/tooling)
73-- Example: `feat: add system and tool message display with visibility controls`
74-- Always use lowercase for the type and description
src/components/App.tsx+21−8
@@ -5,8 +5,9 @@ import { useModels, type Model } from "@/src/hooks/api/useModels";
55 import MessageList from "@/src/components/MessageList";
66 import Welcome from "@/src/components/Welcome";
77 import Sidebar from "@/src/components/Sidebar";
8-import { useTheme } from "../hooks/useTheme";
9-import MessageEditor from "./MessageEditor";
8+import { useTheme } from "@/src/hooks/useTheme";
9+import { useLocalStorage } from "@/src/hooks/useLocalStorage";
10+import MessageEditor from "@/src/components/MessageEditor";
1011
1112 export type AppContextType = {
1213 selectedModel: Model | null;
@@ -41,13 +42,25 @@ export function useAppContext(): AppContextType {
4142 export default function App() {
4243 const { themeMode, handleThemeChange } = useTheme();
4344 const { data: modelsData, isLoading: isModelsLoading, error: modelsError } = useModels();
44-
45- const [selectedModel, setSelectedModel] = useState<Model | null>(null);
46- const [maxPromptLength, setMaxPromptLength] = useState<number | null>(null);
47- const [userPrompt, setUserPrompt] = useState<string>("");
4845 const [selectedThreadId, setSelectedThreadId] = useState<number | null>(null);
49- const [showSystemMessages, setShowSystemMessages] = useState<boolean>(true);
50- const [showToolMessages, setShowToolMessages] = useState<boolean>(true);
46+
47+ const [selectedModel, setSelectedModel] = useLocalStorage<Model | null>(
48+ "app.selectedModel",
49+ null
50+ );
51+ const [maxPromptLength, setMaxPromptLength] = useLocalStorage<number | null>(
52+ "app.maxPromptLength",
53+ null
54+ );
55+ const [userPrompt, setUserPrompt] = useLocalStorage<string>("app.userPrompt", "");
56+ const [showSystemMessages, setShowSystemMessages] = useLocalStorage<boolean>(
57+ "app.showSystemMessages",
58+ true
59+ );
60+ const [showToolMessages, setShowToolMessages] = useLocalStorage<boolean>(
61+ "app.showToolMessages",
62+ true
63+ );
5164
5265 return (
5366 <AppContext.Provider
src/components/MessageEditor.tsx+6−6
@@ -2,12 +2,12 @@
22
33 import { useAutoResizeTextarea } from "@/src/hooks/useAutoResizeTextarea";
44 import { useState } from "react";
5-import Button from "./Button";
6-import PaperPlaneIcon from "./icons/PaperPlaneIcon";
7-import TrashIcon from "./icons/TrashIcon";
8-import { useNewThread } from "../hooks/api/useNewThread";
9-import { useAppContext } from "./App";
10-import { useNewThreadMessage } from "../hooks/api/useNewThreadMessage";
5+import Button from "@/src/components/Button";
6+import PaperPlaneIcon from "@/src/components/icons/PaperPlaneIcon";
7+import TrashIcon from "@/src/components/icons/TrashIcon";
8+import { useNewThread } from "@/src/hooks/api/useNewThread";
9+import { useAppContext } from "@/src/components/App";
10+import { useNewThreadMessage } from "@/src/hooks/api/useNewThreadMessage";
1111
1212 export default function MessageEditor() {
1313 const [userMessage, setUserMessage] = useState("");
src/components/MessageList.tsx+6−6
@@ -2,13 +2,13 @@
22
33 import { useAppContext } from "@/src/components/App";
44 import { useThreadMessages } from "@/src/hooks/api/useThreadMessages";
5-import { Message } from "../lib/db/schema";
5+import { Message } from "@/src/lib/db/schema";
66 import ReactMarkdown from "react-markdown";
77 import remarkGfm from "remark-gfm";
88 import rehypeHighlight from "rehype-highlight";
99 import { useEffect, useRef, useState } from "react";
10-import Button from "./Button";
11-import TrashIcon from "./icons/TrashIcon";
10+import Button from "@/src/components/Button";
11+import TrashIcon from "@/src/components/icons/TrashIcon";
1212
1313 function BaseMessage({
1414 message,
@@ -33,7 +33,7 @@ function BaseMessage({
3333
3434 return (
3535 <div
36- className={`flex min-w-64 flex-col p-2 text-neutral-500 dark:text-neutral-500 ${justifyClass} ${alignClass}`}
36+ className={`message flex min-w-64 flex-col p-2 text-neutral-500 dark:text-neutral-500 ${justifyClass} ${alignClass}`}
3737 >
3838 <div className={`${alignClass}`}>{children}</div>
3939 <div
@@ -114,9 +114,9 @@ export default function MessageList() {
114114 currentMessageCount > 0
115115 ) {
116116 // Scroll the last message into view
117- const lastMessageElement = listRef.current.querySelector(":scope > *:last-child");
117+ const lastMessageElement = listRef.current.querySelector(".message:last-child");
118118 if (lastMessageElement) {
119- (lastMessageElement as HTMLElement).scrollIntoView({ behavior: "smooth", block: "end" });
119+ (lastMessageElement as HTMLElement).scrollIntoView({ behavior: "smooth", block: "start" });
120120 }
121121 }
122122 prevMessageCount.current = currentMessageCount;
src/components/Modal.tsx+0−49
@@ -1,49 +0,0 @@
1-"use client";
2-
3-import { useEffect, type ReactNode } from "react";
4-import XIcon from "@/src/components/icons/XIcon";
5-
6-type ModalProps = {
7- isOpen: boolean;
8- onClose: () => void;
9- children: ReactNode;
10-};
11-
12-export default function Modal({ isOpen, onClose, children }: ModalProps) {
13- useEffect(() => {
14- if (!isOpen) return;
15-
16- const handleEscape = (e: KeyboardEvent) => {
17- if (e.key === "Escape") {
18- onClose();
19- }
20- };
21-
22- document.addEventListener("keydown", handleEscape);
23- return () => {
24- document.removeEventListener("keydown", handleEscape);
25- };
26- }, [isOpen, onClose]);
27-
28- if (!isOpen) return null;
29-
30- return (
31- <div className="fixed inset-0 z-50 flex items-center justify-center">
32- {/* Overlay */}
33- <div className="absolute inset-0 bg-black/80" onClick={onClose} aria-hidden="true" />
34- {/* Modal */}
35- <div className="relative z-10 w-full max-w-lg rounded-lg bg-neutral-50 p-6 shadow-lg dark:bg-neutral-900">
36- {/* Close button */}
37- <button
38- onClick={onClose}
39- className="absolute right-4 top-4 rounded p-1 text-neutral-600 hover:bg-neutral-200 hover:text-neutral-800 dark:text-neutral-400 dark:hover:bg-neutral-800 dark:hover:text-neutral-200"
40- aria-label="Close modal"
41- >
42- <XIcon className="h-5 w-5" />
43- </button>
44- {/* Content */}
45- <div>{children}</div>
46- </div>
47- </div>
48- );
49-}
src/components/Sidebar.tsx+2−7
@@ -1,12 +1,11 @@
11 "use client";
22
33 import BowtieIcon from "@/src/components/icons/BowtieIcon";
4-import GearIcon from "@/src/components/icons/GearIcon";
54 import PlusIcon from "@/src/components/icons/PlusIcon";
65 import { useAppContext } from "@/src/components/App";
76 import Button from "@/src/components/Button";
8-import ChevronDownIcon from "./icons/ChevronDownIcon";
9-import { useThreads } from "../hooks/api/useThreads";
7+import ChevronDownIcon from "@/src/components/icons/ChevronDownIcon";
8+import { useThreads } from "@/src/hooks/api/useThreads";
109
1110 export default function Sidebar() {
1211 const { selectedThreadId, setSelectedThreadId } = useAppContext();
@@ -32,10 +31,6 @@ export default function Sidebar() {
3231 <PlusIcon className="h-4 w-4" />
3332 New Thread
3433 </Button>
35- <Button>
36- <GearIcon className="h-4 w-4" />
37- Settings
38- </Button>
3934 </div>
4035 <div className="flex flex-col gap-4">
4136 <label className="px-2 text-neutral-500">
src/components/Welcome.tsx+22−1
@@ -1,8 +1,14 @@
11 "use client";
22
33 import SettingsForm from "@/src/components/SettingsForm";
4+import Button from "@/src/components/Button";
5+import GearIcon from "@/src/components/icons/GearIcon";
6+import { useState } from "react";
7+import XIcon from "@/src/components/icons/XIcon";
48
59 export default function Welcome() {
10+ const [isSettingsOpen, setIsSettingsOpen] = useState(false);
11+
612 return (
713 <div className="mx-auto w-full max-w-5xl">
814 <div className="m-8 flex flex-col gap-4 rounded-lg bg-neutral-200 p-8 dark:bg-neutral-800">
@@ -15,7 +21,22 @@ export default function Welcome() {
1521
1622 <hr className="my-4 border-neutral-300 dark:border-neutral-700" />
1723
18- <SettingsForm />
24+ {!isSettingsOpen && (
25+ <Button onClick={() => setIsSettingsOpen(true)}>
26+ <GearIcon className="h-4 w-4" />
27+ Settings
28+ </Button>
29+ )}
30+
31+ {isSettingsOpen && (
32+ <>
33+ <Button onClick={() => setIsSettingsOpen(false)}>
34+ <XIcon className="h-4 w-4" />
35+ Close Settings
36+ </Button>
37+ <SettingsForm />
38+ </>
39+ )}
1940 </div>
2041 </div>
2142 );
src/hooks/useLocalStorage.ts+41−0
@@ -0,0 +1,41 @@
1+import { useState } from "react";
2+
3+/**
4+ * Custom hook for persisting state to localStorage.
5+ *
6+ * @param key - The localStorage key
7+ * @param initialValue - The initial value if no stored value exists
8+ * @returns A tuple of [value, setValue] similar to useState
9+ */
10+export function useLocalStorage<T>(
11+ key: string,
12+ initialValue: T
13+): [T, (value: T | ((prev: T) => T)) => void] {
14+ const [storedValue, setStoredValue] = useState<T>(() => {
15+ if (typeof window === "undefined") {
16+ return initialValue;
17+ }
18+
19+ try {
20+ const item = window.localStorage.getItem(key);
21+ return item ? (JSON.parse(item) as T) : initialValue;
22+ } catch {
23+ return initialValue;
24+ }
25+ });
26+
27+ const setValue = (value: T | ((prev: T) => T)) => {
28+ try {
29+ const valueToStore = value instanceof Function ? value(storedValue) : value;
30+ setStoredValue(valueToStore);
31+
32+ if (typeof window !== "undefined") {
33+ window.localStorage.setItem(key, JSON.stringify(valueToStore));
34+ }
35+ } catch {
36+ // Silently fail if localStorage is unavailable
37+ }
38+ };
39+
40+ return [storedValue, setValue];
41+}
src/hooks/useTheme.ts+7−2
@@ -1,4 +1,6 @@
1-import { useEffect, useState } from "react";
1+import { useEffect } from "react";
2+import { useLocalStorage } from "@/src/hooks/useLocalStorage";
3+
24 /**
35 * Custom hook for managing theme mode (device, dark, or light).
46 * Automatically applies the theme and listens for system preference changes when in device mode.
@@ -8,7 +10,10 @@ import { useEffect, useState } from "react";
810 * - `handleThemeChange` - Function to change the theme mode
911 */
1012 export function useTheme() {
11- const [themeMode, setThemeMode] = useState<"device" | "dark" | "light">("device");
13+ const [themeMode, setThemeMode] = useLocalStorage<"device" | "dark" | "light">(
14+ "theme.mode",
15+ "device"
16+ );
1217
1318 const applyTheme = (mode: "device" | "dark" | "light") => {
1419 let shouldBeDark = false;